是否可以提供多个约束作为类型参数?

时间:2019-02-23 15:01:45

标签: c# generics types

我有以下情况:

public class SomeClass {/*… */}
public interface ISomeInterface {/*… */}

public T GetFirst<T>(){/*… gets the first object of type T */}
public void AddElement<T> () where T: SomeClass, ISomeInterface {/*… */}

我想做的就是调用GetFirst,其Type参数是从SomeClass和ISomeInterface派生的任何东西。

例如,如果我有以下课程:

class A : SomeClass, ISomeInterface { }
class B : SomeClass, ISomeInterface { }
class C : SomeClass, ISomeInterface { }

并且我想指定GetFirst()的类型参数以返回A,B或C中的任何一个,因此结果可以满足AddElement的类型约束:

void MyFunction()
{
    t result = GetFirst<t>() where t : SomeClass, ISomeInterface;
    AddElement(result);
}

在C#中提供类型参数时是否可以定义多个类型约束?

1 个答案:

答案 0 :(得分:1)

您提供的用法示例仅在以下情况下可用:

  1. 您希望提供的已知类型,或者
  2. C#支持intersection types(例如like TypeScript does)。

#1可能看起来像这样:

void MyFunction()
{
    KnownType result = GetFirst<KnownType>();
    AddElement(result);
}

public class KnownType: SomeClass, ISomeInterface {...}

public T GetFirst<T>() => this.objects.OfType<T>().First();

#2当前无法使用,因为C#没有交集类型。

相关问题