理解C#通用和上播

问题描述 投票:1回答:1

请看下面的例子。

class A : ISomething
class B : ISomething
class C : ISomething

private void AcceptsISomething<T>(T input) where T : ISomething
{
    if (input is A)
    if (input is B)
    if (input is C)
}

private void AcceptsISomething(ISomething input)
{
    if (input is A)
    if (input is B)
    if (input is C)
}

以上两个例子的功能有什么不同?

我认为没有区别,因为这两个功能都保证了 input 已实施 ISomething在这两个函数中 input 可以成功地与实现了 ISomething.

但我也认为,如果真的没有区别,那就没有理由有笑料功能了。where 存在。

c#
1个回答
2
投票

好吧,在你的例子中,其实没有什么区别,但通用函数的WHERE约束确实非常有用。通过在泛型函数中添加WHERE约束,你可以确保使用的类型是由约束中的类型派生出来的(或者是)。通过这种方式,你也可以使用这种类型的函数。

https:/docs.microsoft.comen-usdotnetcsharpprogramming-guidegenericsconstraints-on-type-parameters。


2
投票

你的例子很简单,但一般来说,有很多事情你可以用 where 只有。

多重制约因素

void AcceptsISomething<T>(T input) where T : ISomething, new()

继承权

class Base<T> where T : ISomething

class ChildA : Base<A>

返回值

private T Modify<T>(T input) where T : ISomething

var value = new A();
value = Modify(value); // vs (A)Modify(value)

混凝土类型

private void AcceptsISomething<T>(T input) where T : ISomething
{
    Console.WriteLine(typeof(T));
}

A value = null;
AcceptsISomething(null); // prints "A" although argument is null
© www.soinside.com 2019 - 2024. All rights reserved.