[英]Using reflection and an Interface in a constructor to initialize in C#
我正在开发一项服务,以从许多远程数据库收集数据并将其编译为master数据库。 我有一个包含两个数据库之间通用数据的接口。 该接口还充当我的模型和ViewModel之间的链接。
我想从RemoteDatabase的实例中获取数据,然后将所有数据放入MasterDatabase的实例中。
public interface IInterface
{
//Common interface properties in both databases
long PK { get; set; }
Nullable<long> RUN_ID { get; set; }
string Recipe_Name { get; set; }
string Notes { get; set; }
//Lots more properties from a database
}
class RemoteDatabase : IInterface
{
//Common interface properties in both databases
public long PK { get; set; }
public Nullable<long> RUN_ID { get; set; }
public string Recipe_Name { get; set; }
public string Notes { get; set; }
//Lots more properties from a database
}
class MasterDatabase : IInterface
{
//Additional properties that Remote Database doesn't have
public int locationFK { get; set; }
//Common interface properties from database
public long PK { get; set; }
public Nullable<long> RUN_ID { get; set; }
public string Recipe_Name { get; set; }
public string Notes { get; set; }
//Lots more properties from a database
public MasterDatabase(IInterface iInterface)
{
var interfaceProps = typeof(IInterface).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in interfaceProps)
{
p.Name;
}
}
}
我试图投射对象,但是提供了无效的投射异常,据我了解(尽管它们具有共同的祖先,并不意味着它们可以投射dog == animal,fish == animal,但是dog!= fish,但我想要获得IAnimal中定义的通用属性。
由于无法投射,因此我想使用反射,以便如果接口更新,则MasterDatabase类中的所有新对象将自动更新。 我使用反射从接口获取所有属性,但是现在我如何使用propertyInfo.name获取MasterDatabase类中的值。
也许我缺少明显的东西,或者有更好的方法可以做到这一点。 感谢您的帮助或建议。
先感谢您。
您需要使用this
属性作为目标调用PropertyInfo对象上的SetValue
。 您传递的值应使用构造函数参数上的相应GetValue
调用来检索:
foreach (PropertyInfo p in interfaceProps)
{
p.SetValue(this, p.GetValue(iInterface, null), null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.