c#通用约束

本文关键字:约束 | 更新日期: 2023-09-27 17:50:44

我需要从Interfacegeneric field中获得一些classes inherit这样的

public Interface ICommon<Ttype>
{
  Ttype Filed{get;set;}
}
public Class class1:Icommon<int>
{
  int Filed{get;set;}
}
public Class class2:Icommon<double>
{
  double Filed{get;set;}
}

我创建了一个generic class with constraints,它使用class1class2类来进行一些操作,如:

public Class GenericClass<Ttype,Tcommon> where Ttype:ICommon<Tcommon>
{
    //forexample
    public Ttype someOperation(Ttype x)
    {
    var a=x.Field;
    //.............
    }
}

每次我使用GenericClass时,我必须知道我使用的类的type of Field,例如class1class2,以便能够传递它以匹配generic constraint

有没有一种方法可以这样写GenericClass:

public Class GenericClass<Ttype,Tcommon> where Ttype:**ICommon**
{
  //forexample
  public Ttype someOperation(Ttype x)
  {
    var a=x.Field;
    //.............
  }
}
ICommon而不写<TCommon> ??

更新:或者如何编辑ICommon interface像这样

 public Interface ICommon
    {
      Ttype Filed{get;set;}
    }

c#通用约束

我希望我明白你的意思:

public interface ICommon<T>
{
    T Field { get; set; }
}
public class GenericClass<T>
{
    public ICommon<T> SomeOperation(ICommon<T> x)
    {
        // do your stuff
    }
}

简短的回答是:不。

你需要告诉编译器泛型参数的类型。实际上,GenericClass<int>GenericClass<string>是CLR中两个不同的类。