【发布时间】:2012-12-14 14:04:49
【问题描述】:
给定一个场景,
Class Car: Transport,
Class Bus: Transport,
Interface Transport,Get(): Generics Method
有可能做这样的事情吗?
Transport t= Get<"Car">(string color);
public T Get<T>(string color)
{
return new T(color);
}
P/S:有理由将其动态分配为字符串,而不管返回类型如何。
【问题讨论】:
-
不是你建议的方式。在您的情况下,“Car”、“Bus”、“Bike”将始终是一种字符串。您可以打开字符串,创建并返回适当的对象。
-
你不想那样做,检查你的设计。
-
看到了,没有回答我的问题:)
-
(Transport)Activator.CreateInstance(Type.GetType("....")) -
@Roylee 我知道这不能回答你的问题,所以我只是把它作为评论,但我只是想指出,为了让该代码能够编译,你需要
Get<T>(string)方法中泛型类型参数T的where T : new()约束。
标签: c# generics reflection