为什么要使用在C#泛型约束 [英] Why use generic constraints in C#

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

问题描述

我读过关于C#泛型MSDN上的优秀文章。

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?

例如,如果我用code是这样的:

For example, if I use code like this:

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

我不能切换 T 的所有引用这一类 ISomething

什么是使用这种方法的好处?

What's the benefit of using this approach?

感谢

推荐答案

您会问,我不能切换 T 的所有引用这一类 ISomething ?所以,我想你的意思比较:

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 。如果省略了其中T:ISomething ,那么你将无法访问 SomeProperty ,因为 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#泛型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆