任何人都可以告诉我是否有一种方法可以使用泛型来限制泛型类型参数T:
Int16Int32Int64UInt16UInt32UInt64我知道的where关键字,但无法找到一个接口只有这些类型,
就像是:
static bool IntegerFunction<T>(T value) where T : INumeric
Run Code Online (Sandbox Code Playgroud) 是否可以在C#泛型中实现基本算法(至少是加法),就像使用C++模板一样?我已经尝试了一段时间来让它们起作用,但是C#不允许你多次声明相同的泛型类型,就像你可以使用模板一样.
广泛的谷歌搜索没有提供答案.
编辑:谢谢,但我正在寻找的是一种在编译时进行算术运算的方法,在泛型类型中嵌入像教会数字这样的东西.这就是为什么我把我做过的文章联系起来的原因.算术在泛型类型,而不是算术上的情况下,泛型类型.
我本来应该写一个方法,它将在整数,浮点或双精度的集合上执行加法.我打算写三个方法,遍历三种不同的类型执行加法并返回值.有用.我只是很好奇,这可以在一个方法中完成,其中类型传递给泛型类型,类似于
public static T SUM<T>(IEnumerable<T> dataCollection)
{
T total;
foreach(var value in dataCollection)
total += value;
return total;
}
Run Code Online (Sandbox Code Playgroud)
我能够通过正常的三种方法实现解决它,但只是好奇,它甚至可能吗?
谢谢,
如果我有一个被限制为类型'int'的泛型方法,那么我当然应该能够将一个整数转换为泛型T类型.例如...
public T ExampleMethod<T>(int unchanged) where T : int
{
return (T)unchanged;
}
Run Code Online (Sandbox Code Playgroud)
...编译器抱怨无法将类型'int'转换为'T',但我有一个约束,表明目标是整数.那肯定应该有用吗?
更新:
实际情况是我想要一个返回枚举值的辅助方法.所以我理想的助手方法会更像这样....
public T GetAttributeAsEnum<T>(XmlReader reader, string name) where T : enum
{
string s = reader.GetAttribute(name);
int i = int.Parse(s);
return (T)i;
}
Run Code Online (Sandbox Code Playgroud)
......并像这样使用它......
StateEnum x = GetAttributeAsEnum<StateEnum>(xmlReader, "State");
CategoryEnum y = GetAttributeAsEnum<CategoryEnum>(xmlReader, "Category");
OtherEnum z = GetAttributeAsEnum<OtherEnum>(xmlReader, "Other");
Run Code Online (Sandbox Code Playgroud)
......但你无法通过枚举来约束.