C# 让编译器知道泛型有一个字段
假设我有一个通用类型为getCountry的方法:C# 让编译器知道泛型有一个字段,c#,.net,C#,.net,假设我有一个通用类型为getCountry的方法: public T GetCountry<T>(int portalID) { T theCountry = (T)Activator.CreateInstance(typeof(T)); theCountry.id = "AR"; if(portalID == 1) theCountry.id = "ARG"; return theCountry; } public T GetCountry(int
public T GetCountry<T>(int portalID)
{
T theCountry = (T)Activator.CreateInstance(typeof(T));
theCountry.id = "AR";
if(portalID == 1) theCountry.id = "ARG";
return theCountry;
}
public T GetCountry(int-portalID)
{
T theCountry=(T)Activator.CreateInstance(typeof(T));
country.id=“AR”;
如果(portalID==1)country.id=“ARG”;
返回国家;
}
当然,这不起作用,因为编译器不知道t内部有一个名为“id”的字段
我不能做其他的解决方案,比如把放在t extensed AbstractCountry
的地方,或者别的什么,因为这些国家/地区类是顶级类,我无法访问代码来为它们创建父类。代码不是我的(不幸的是设计得很糟糕)。这意味着我也不能为不同的国家/地区类型创建构造函数,并使用Activator类将id作为参数发送,就我个人而言,这就是我对泛型的了解的终点
有什么方法可以实现我想做的吗?谢谢大家 是的,使用C#中的。创建实例时使用
dynamic
,这允许您在实例上使用任意成员(“后期绑定”)。如果T
没有具有该名称的属性或字段,则会引发运行时错误
在返回对象之前,将其投射回T
public T GetCountry<T>(int portalID)
{
dynamic theCountry = Activator.CreateInstance(typeof(T));
theCountry.id = "AR";
if(portalID == 1) theCountry.id = "ARG";
return (T)theCountry;
}
public T GetCountry(int-portalID)
{
dynamicthecountry=Activator.CreateInstance(typeof(T));
country.id=“AR”;
如果(portalID==1)country.id=“ARG”;
返回(T)国家;
}
与动态
功能相反,您可以使用通用参数约束
public interface IIdentifier
{
string Id { get; set; }
}
public static T GetCountry<T>(int portalID) where T : IIdentifier
{
T theCountry = (T)Activator.CreateInstance(typeof(T));
theCountry.Id = "AR";
if (portalID == 1) theCountry.Id = "ARG";
return theCountry;
}
公共接口标识器
{
字符串Id{get;set;}
}
公共静态T GetCountry(int portalID),其中T:IIIdentifier
{
T theCountry=(T)Activator.CreateInstance(typeof(T));
country.Id=“AR”;
如果(portalID==1)country.Id=“ARG”;
返回国家;
}
IIdentifier
可以是一些基本类型,它具有所需的所有属性。如果没有通用的基类型,那么动态
就是最好的选择
值得注意的是,当您将dynamic与没有名为
Id
的成员的类型一起使用时,运行时将失败,但当您使用泛型约束时,您将无法编译它,这将很好,而不是在运行时无声地失败。是的,当您说您的PS时,我已经编辑了帖子。太快了,天哪。谢谢是的,正如我在问题中所说,没有共同的接口或任何东西。我也不能编辑它们。很遗憾=(.谢谢!@Damieh如果没有常见的基类型,那么请使用动态
。请务必阅读我的编辑。