c#通用约束
本文关键字:约束 | 更新日期: 2023-09-27 17:50:44
我需要从Interface
和generic 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
,它使用class1
和class2
类来进行一些操作,如:
public Class GenericClass<Ttype,Tcommon> where Ttype:ICommon<Tcommon>
{
//forexample
public Ttype someOperation(Ttype x)
{
var a=x.Field;
//.............
}
}
每次我使用GenericClass
时,我必须知道我使用的类的type of Field
,例如class1
或class2
,以便能够传递它以匹配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;}
}
我希望我明白你的意思:
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中两个不同的类。