本文介绍了为什么在 C# 中使用泛型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MSDN 上阅读了一篇关于 C# 泛型的优秀文章.

I've read an excellent article on MSDN regarding Generics in C#.

出现在我脑海中的问题是 - 为什么我应该使用通用约束?

The question that popped in my head was - why should i be using generic constraints?

例如,如果我使用这样的代码:

For example, if I use code like this:

public class MyClass<T> where T : ISomething
{
}

我不能用 ISomething 切换这个类中 T 的所有引用吗?

can't I switch ALL references of T in this class with ISomething?

使用这种方法有什么好处?

What's the benefit of using this approach?

推荐答案

你问,我不能用 ISomething 切换这个类中 T 的所有引用吗?"所以我认为你的意思是比较:

You ask, "can't I switch ALL references of T in this class with ISomething?" So I think you mean to compare:

public class MyClass<T> where T : ISomething
{
    public T MyProperty { get; set; }
}

与:

public class MyClass
{
    public ISomething MyProperty { get; set; }
}

在第二个示例中,MyProperty 仅保证是 ISomething 的实例.在第一个示例中,MyProperty 是任何 T,即使它是 ISomething 的特定子类型.考虑一个 ISomething 的具体实现:

In the second example, MyProperty is only guaranteed to be an instance of ISomething. In the first example, MyProperty is whatever T is, even if that is a specific subtype of ISomething. Consider a concrete implementation of ISomething:

public class MySomething : ISomething
{
    public string MyOtherProperty { get; set; }
}

现在,如果我们使用第一个通用示例,我们可以:

Now, if we use the first, generic, example, we could have:

MyClass<MySomething> myClass = new MyClass<MySomething>();
Console.WriteLine(myClass.MyProperty.MyOtherProperty);

另一方面,如果我们使用第二个示例,我们将无法访问 MyOtherProperty,因为它只知道是一个 ISomething:

On the other hand, if we used the second example, we wouldn't be able to access MyOtherProperty since it's only known to be an ISomething:

MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyProperty.MyOtherProperty); // Won't compile, no property "MyOtherProperty"

另一方面,这些类型约束有用的原因是您可以引用MyProperty(类型T)并访问ISomething.换句话说,如果 ISomething 被声明为:

On a different note, the reason these type constraints are useful is that you can refer to MyProperty (type T) and access members of ISomething. In other words, if ISomething were declared like:

public interface ISomething
{
    public string SomeProperty { get; set; }
}

然后您可以访问MyProperty.SomeProperty.如果您省略了 where T : ISomething 那么您将无法访问 SomeProperty 因为 T 只会被称为 T代码>对象.

Then you could access MyProperty.SomeProperty. If you omitted the where T : ISomething then you wouldn't be able to access SomeProperty since T would only be known to be of type object.

这篇关于为什么在 C# 中使用泛型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:16