Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否可以提供多个约束作为类型参数?_C#_Generics_Types - Fatal编程技术网

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

C# 是否可以提供多个约束作为类型参数?,c#,generics,types,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()的类型参数

我有以下情况:

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()的类型参数来返回A、B或C中的任意一个,这样结果就可以满足AddElement的类型约束:

void MyFunction()
{
    t result = GetFirst<t>() where t : SomeClass, ISomeInterface;
    AddElement(result);
}
void MyFunction()
{
t result=GetFirst(),其中t:SomeClass,接口;
加法(结果);
}

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

您提供的使用示例仅在以下情况下才可能:

  • 您希望提供已知类型,或者
  • C#支持(例如)
  • #1
    可能如下所示:

    void MyFunction()
    {
        KnownType result = GetFirst<KnownType>();
        AddElement(result);
    }
    
    public class KnownType: SomeClass, ISomeInterface {...}
    
    public T GetFirst<T>() => this.objects.OfType<T>().First();
    
    void MyFunction()
    {
    KnownType结果=GetFirst();
    加法(结果);
    }
    公共类KnownType:SomeClass,接口{…}
    public T GetFirst()=>this.objects.OfType().First();
    

    #2
    目前不可能,因为C没有交集类型。

    您已经得到了
    AddElement
    的约束-我不确定为什么您不只是将其应用于
    GetFirst
    …这不是类型约束,这是类型约束。您只能提供一个。@JonSkeet他所说的情况是,您需要满足这两个约束的所有项,而不是修改GetFirst()可以返回的类型。就像我想从实现IComparable和IEnumerable的列表中获取所有对象一样,无法将其指定为类型参数的调用方。@BryceWagner:如果是这样,那么
    GetFirst
    就不应该是泛型的。从根本上说,我认为这个问题目前还不清楚——我怀疑OP误解了泛型,但如果没有更多的信息,就很难确切知道误解是什么,或者如何帮助他们。是的,我的意思正是Brice Wagner所说的。
    void MyFunction()
    {
        KnownType result = GetFirst<KnownType>();
        AddElement(result);
    }
    
    public class KnownType: SomeClass, ISomeInterface {...}
    
    public T GetFirst<T>() => this.objects.OfType<T>().First();