[英]How to add Additional Properties to a Class without inheritance in C#
我有一个MobileInfo
类
public class MobileInfo
{
public string MobileName { get; set; }
public string MobileOS { get; set; }
}
我需要再添加一个属性
public string MobileModel { get; set; }
我在主项目中的100多个类文件中实现了Model
类,而MobileInfo
的基类在Remote Server中。 我需要添加属性而不继承和修改基类。
注意:不要创建派生类来添加此属性,因为我无法更改基类实例。 我拥有访问该实例的权限,并且可以在不触摸基类的情况下添加属性。
System.ComponentModel.TypeDescriptor()
var curPhone = new MobileInfo();
curPhone.MobileName = "iphone";
curPhone.MobileOS = "ios";
TypeDescriptor.AddAttributes(typeof(MobileInfo), new simpleAttribute());
AttributeCollection collection = TypeDescriptor.GetAttributes(curPhone);
simpleAttribute attr = ((simpleAttribute)collection[typeof(simpleAttribute)]);
if (attr != null)
{
attr.MobileModul = "s6";
//MessageBox.Show(attr.MobileModul);
}
}
public class simpleAttribute : Attribute
{
public string MobileModul { get; set; }
}
您不能在不更改代码的情况下为类添加属性。
使用System.Reflection.Emit
方法,您可以创建动态程序集,该程序集将复制MobileInfo
和子孙类的整个层次结构。 请参见为set parent 创建类型和方法 。 之后,您可以将必需的属性添加到MobileInfo
生成的副本中。 接下来,您应该配置抽象工厂,该工厂将在查询类型时返回生成的类型。
但这很困难。 我强烈建议您重新构建项目架构。 由于MobileInfo
在远程服务器上,因此您的本地数据模型应具有MobileInfo
的副本,并且不应继承远程MobileInfo
,此外,您还应具有从远程服务器数据模型对象映射到本地的方法。 因此,您可以使用本地MobileInfo
任何所需的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.