C# 如何在泛型方法中返回与参数相关的类型?

C# 如何在泛型方法中返回与参数相关的类型?,c#,C#,我试图编写一个方法,返回与给定泛型类型参数相关的对象或集合。 结构如下: public interface IBaseClass{ } public class AnEntityClass:IBaseClass{ public string SomeValue { get; set } } public class AnotherEntityClass:IBaseClass{ public string SomeValue { get; set } } public cla

我试图编写一个方法,返回与给定泛型类型参数相关的对象或集合。 结构如下:

public interface IBaseClass{
}

public class AnEntityClass:IBaseClass{
    public string SomeValue { get; set }
}

public class AnotherEntityClass:IBaseClass{
    public string SomeValue { get; set }
}

public class TestClass<T> {
    public string AnotherValue { get; set; }
    public T GenericValue { get; set }
}

public TestClass<List<AnEntityClass>> AMethodReturnsGenericList(){
    return new TestClass<List<AnEntityClass>>();
}

public TestClass<AnotherEntityClass> AMethodReturnsAnObject(){
    return new TestClass<AnotherClass>();
}


公共接口IBaseClass{
}
公共类一个实体类:IBaseClass{
公共字符串SomeValue{get;set}
}
公共类AnotherEntityClass:IBaseClass{
公共字符串SomeValue{get;set}
}
公共类TestClass{
公共字符串另一个值{get;set;}
公共T GenericValue{get;set}
}
公共测试类AMethodReturnsGenericList(){
返回新的TestClass();
}
公共测试类AMethodReturnsAnObject(){
返回新的TestClass();
}
我尝试了一种如下所示的方法,但它给出了一个编译时错误

先将其转换为对象,然后再将其转换为TestClass,这是可行的,但对我来说似乎不是一个好的解决方案

正确的做法是什么

//cannot implicitly convert ....
public TestClass<T> DoSomeWork<T>(string methodType)
{
    if(methodType=="collection")
        return AMethodReturnsGenericList();
    else if(methodType=="object")
        return AMethodReturnsAnObject();

}
//无法隐式转换。。。。
公共测试类DoSomeWork(string methodType)
{
if(methodType==“集合”)
return-AMethodReturnsGenericList();
else if(methodType==“对象”)
return-AMethodReturnsAnObject();
}

如果有人打电话给DoSomeWork(“收集”),你希望发生什么
AMethodReturnsGenericList()
不返回
TestClass
。。。您真的确定
DoSomeWork
应该是一个通用方法吗?添加约束“where T:IBaseClass”是否解决了您提到的问题?实际上我想做的就是这样。我有许多返回泛型类型的方法,我想写一个方法,作为路由器方法工作,并公开给其他类@琼斯基特。当我考虑你的答案时,它看起来像是一个设计问题。不,它不是。例如,您仍然可以调用
DoSomeWork
,那么您希望发生什么呢?是的,看起来仍然容易出错。据我从你的回答中了解,这不是一种通用方法。你对那个案子有什么建议@JonSkeet?我有一些方法,它们返回TestClass,其中T可以是一个EntityClass或另一个EntityClass。我怎样才能编写一个代理方法,它向其他类公开,并调用我上面提到的方法并返回它们的结果呢?恐怕我对您试图实现的目标了解得不够。目前,我建议使用不同的方法,因为您无法轻松地表示Single方法应该以安全的方式返回什么。