gpt4 book ai didi

c# - 让编译器知道 Generic 有一个字段

转载 作者:行者123 更新时间:2023-12-03 03:05:15 24 4
gpt4 key购买 nike

假设我有一个名为 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;
}

当然这是行不通的,因为编译器不知道T里面有一个名为“id”的字段。

我无法执行替代解决方案,例如放置 where T extends AbstractCountry 或其他任何解决方案,因为这些国家/地区类是顶级类,并且我无权访问代码来为它们创建父级。该代码不是我的(不幸的是设计得很糟糕)。这意味着我也无法为不同的国家/地区类型创建构造函数并使用 Activator 类将 id 作为参数发送,就我个人而言,这就是我对泛型的了解。

有什么办法可以实现我想要做的事情吗?谢谢大家!!!

最佳答案

创建实例时使用动态,这允许您在其上使用任意成员(“后期绑定(bind)”)。如果 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;
}

关于c# - 让编译器知道 Generic 有一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com