复制实现此相同接口的所有参数

时间:2014-02-06 13:00:41

标签: c# interface

我正在寻找最佳解决方案,例如: (让我们用伪代码说话!)

public interface IObj
{
    string propertyX;
    string propertyY;
}

public class ObjectA : IObj
{
    string propertyX;
    string propertyY;
}

public class ObjectB: IObj
{
    string propertyX;
    string propertyY;

    public ObjectB(ObjectA)
    {
        // HERE I WANT TO GET ALL Properties that are from ObjectA that is from IObj
        // without assigne this.propertyX=ObjectA.propertyX
    }
}

有没有简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:2)

要实现目标,您需要做的就是: - 从IObj界面获取所有属性 - 获取ObjectA课程的所有属性 - 获取ObjectB课程的所有属性 - 加入来自IObj界面的属性名称的集合,以及来自ObjectA的{​​{1}}对属性和来自ObjectB的属性 - 对来自GetValue()

的属性的ObjectASetValue()上的属性进行迭代并调用ObjectB

这是我在LinqPad中抓到的:

void Main()
{
    var a = new ObjectA
    {
        propertyX = Guid.NewGuid().ToString(),
        propertyY = Guid.NewGuid().ToString()
    };
    var b = new ObjectB(a);
    b.Dump();
}


public interface IObj
{
    string propertyX{get;set;}
    string propertyY{get;set;}
}

public class ObjectA : IObj
{
    public string propertyX{get;set;}
    public string propertyY{get;set;}
}

public class ObjectB: IObj
{
    public string propertyX{get;set;}
    public string propertyY{get;set;}

    public ObjectB(ObjectA a)
    {
        var properties = typeof(IObj).GetProperties();
        var objAProperties = typeof(ObjectA).GetProperties();
        var objBProperties = typeof(ObjectB).GetProperties();
        var common = from p in properties
                     from propA in objAProperties
                     from propB in objBProperties
                     where p.Name == propA.Name && p.Name == propB.Name
                     select Tuple.Create(propA, propB);
        foreach(var tuple in common)
        {
            var value = tuple.Item1.GetValue(a);
            tuple.Item2.SetValue(this, value);
        }
    }
}

稍后编辑

在界面上创建扩展方法:

public static class ObjExtesions
{
    public static void CopyProperties(this IObj source, IObj destination)
    {
        var properties = typeof(IObj).GetProperties();
        var objAProperties = source.GetType().GetProperties();
        var objBProperties = destination.GetType().GetProperties();
        var common = from p in properties
                     from propA in objAProperties
                     from propB in objBProperties
                     where p.Name == propA.Name && p.Name == propB.Name
                     select Tuple.Create(propA, propB);
        foreach(var tuple in common)
        {
            var value = tuple.Item1.GetValue(source);
            tuple.Item2.SetValue(destination, value);
        }
    }
}

然后,更改ObjectB构造函数中的代码:

public ObjectB(ObjectA a)
{
    a.CopyProperties(this);
}