泛型函数和类的C#问题 [英] C# problems with generic function and classes
本文介绍了泛型函数和类的C#问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨.
简而言之,我收到一条错误消息:无法从T型转换为int或为double ......".
这是代码
Hi.
To be very brief, I get the error saying "cannot convert from type T to int, or to double ......"
here is the code
public class Class1<t>
{
public Func<t> getter;
public Class1(Func<t> getter)
{
this.getter = getter;
}
}
public class Class2
{
public Class1<bool> boolData;
public Class1<int> intData;
public Class1<long> longData;
public Class1<float> floatData;
public Class1<double> doubleData;
public Class1<string> stringData;
}
public class Main
{
public Class2 data;
public void TryMe<t>(Func<t> getter)
{
if(typeof(T) == typeof(int))
{
data.intData = new Class1<int>(getter);
// ABOVE LINE
}
else if(typeof(T) == typeof(double))
{
data.intData = new Class1<double>(getter);
}
// and so on for bool, long, float and string
}
}
[edit]插入代码块以保留格式. <"和>"字符转义以保留含义...-OriginalGriff [/edit]
[edit]Code block inserted to preserve formatting. "<" and ">" characters escaped to preserve meaning... - OriginalGriff[/edit]
推荐答案
应用复制粘贴时,请确保更新所有相关项. ;)
data. int Data = new Class1< double >(getter);
您正在将class1 double 放入 int Data占位符.
When you apply copy-paste... be sure to update all relevant items. ;)
data.intData = new Class1<double>(getter);
You are putting a class1 double into the intData placeholder.
这篇关于泛型函数和类的C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文