我是 C# 的初学者,并且有问题一直困扰着我。
如果有人提出解决方案,我将不胜感激。
我有一个类似的代码:
public class SomeClass
{
public SomeClass()
{
GenericMethod<Object1>(out result);
....
}
public void GenericMethod<T>(out Result result) where T : Parent
{
T t = new T();
//do something need to be done all parent's child object ( Object1, Object2..)
...somthing same things...
//and do specific things to be done relatively
Handle(t, result);
}
// Object1 is child of Parent
private void Handle(Object1 arg1, out Result result)
{
//do something need to be done for Object1;
}
// Object1 is child of Parent
private void Handle(Object2 arg1, out Result result)
{
//do something need to be done for Object2;
}
....
}
你会发现,我想做的很简单。
在 GenericMethod 中用 Type T 生成指定值,并调用指定的 Handle 方法。它可以在 C++ 中工作,但 C# 一直告诉我喜欢
“无法将 'T' 表达式转换为类型 'Object1'”
我怎么解决这个问题 ?提前谢谢。