gpt4 book ai didi

c# - 为什么在 C# 中使用泛型约束

转载 作者:IT王子 更新时间:2023-10-29 04:13:54 24 4
gpt4 key购买 nike

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

我脑海中浮现的问题是——我为什么要使用通用约束?

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

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

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

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

最佳答案

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

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

与:

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

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

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

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

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

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

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

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

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

然后您可以访问 MyProperty.SomeProperty。如果您省略了 where T : ISomething 那么您将无法访问 SomeProperty 因为 T 只会被认为是类型 对象

关于c# - 为什么在 C# 中使用泛型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4073852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com