在构造函数中使用反射和接口在 C# 中初始化

本文关键字:接口 初始化 构造函数 反射 | 更新日期: 2023-09-27 18:35:27

我正在开发一种服务,用于从许多远程数据库收集数据并将其编译为主数据库。 我有一个接口,其中包含两个数据库之间通用的数据。 该界面还充当我的模型和视图模型之间的链接。

我想从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 类中的值。

也许我错过了一些明显的东西,或者有一个更好的方法来做到这一点。 我感谢任何帮助或建议。

提前谢谢你。

在构造函数中使用反射和接口在 C# 中初始化

您需要

在 PropertyInfo 对象上调用 SetValue,使用 this 作为目标。应使用对构造函数参数的相应GetValue调用来检索传递的值:

foreach (PropertyInfo p in interfaceProps)
{
    p.SetValue(this, p.GetValue(iInterface, null), null);
}