简体   繁体   English

具有指定类型的通用方法

[英]Generic method with specified types

Can I do something like this: 我可以这样做:

public void Foo<T>(int param) where T: MYCLASS1, MYCLASS2

To specify that T will only be MYCLASS1 or MYCLASS2 instance? 要指定T只是MYCLASS1或MYCLASS2实例?

Thank you.. 谢谢..

No, when you specify generic type constraints, the generic type argument must satisfy all the constraints, not just one of them. 不,当您指定泛型类型约束时,泛型类型参数必须满足所有约束,而不仅仅是其中之一。 The code you wrote means that T must inherit both MYCLASS1 and MYCLASS2 , which is not possible since C# doesn't support multiple inheritance. 您编写的代码意味着T必须继承MYCLASS1MYCLASS2 ,这是不可能的,因为C#不支持多重继承。 The generic type constraints can be a combination of: 泛型类型约束可以是以下组合:

  • a base class (only one allowed) 基类(只允许一个)
  • one or several interfaces 一个或几个接口
  • the new() constraint (ie the type must have a parameterless constructor) new()约束(即类型必须具有无参数构造函数)
  • either struct or class (but not both, since a type can't be a value type and a reference type) structclass (但不是两者,因为类型不能是值类型引用类型)

You cannot do that. 你不能这样做。

While adding constraints on a generic type you can list only one class and others have to be interfaces. 在泛型类型上添加约束时,您只能列出一个类,而其他类必须是接口。

This is a valid constraint - 这是一个有效的约束 -

public void Foo<T>(int param) where T: MyClass1, IInterface1, IInterface2

But not this 但不是这个

public void Foo<T>(int param) where T: MyClass1, MyClass2

This is logical, because when you declare a variable of type Foo such as Foo<MyType> , your MyType can derive from MyClass1 , IInterface1 and MyInterface2 but it cannot derive from both MyClass1 and MyClass2 . 这是合乎逻辑的,因为当您声明Foo类型的变量(如Foo<MyType>MyType可以从MyClass1IInterface1MyInterface2派生,但它不能从MyClass1MyClass2

No, generic constraints are always ANDed together. 不,通用约束总是和在一起。 You will have to do a runtime check: 您将不得不进行运行时检查:

public void Foo<T>(int param) {
    if (typeof(T) != typeof(MyClass1) && typeof(T) != typeof(MyClass2))
        throw new ArgumentException("T must be MyClass1 or MyClass2");
    // ...
}

As Thomas points out, you cannot do this. 托马斯指出,你不能这样做。 What you can do however is this: 你可以做的是:

public void Foo<T>(int param) where T: IMyInterface

As long as you know that both MYCLASS1 and MYCLASS2 implement IMyInterface 只要你知道,无论MYCLASS1MYCLASS2实施IMyInterface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM