簡體   English   中英

C#memberwisecopy和后代

[英]C# memberwisecopy and descendants

我認為沒有任何答案,但是在我優雅地進行此操作之前,我會在這里問:

我有一個包含大量數據的父類。 這些僅用於實例化繼承父對象的后代,對其進行修改並產生最終結果。

我看到了如何使用MemberwiseCopy來創建父級的另一個實例,但是我需要一個子級,而不是另一個父級。

我看到兩個答案,我都不喜歡:

1)忘記繼承,在工作副本的字段中制作父副本。

2)將每個字段復制到孩子。

使用反射和自定義屬性? 裝飾要復制到后代的字段,並在實例化期間使用反射遍歷每個修飾的字段並將其值復制到后代。

例:

[AttributeUsage(AttributeTargets.Field)]
class PassDownAttribute : Attribute
{
}

public class TheParent
{
    [PassDown]
    public int field1;
    [PassDown]
    public string field2;
    [PassDown]
    public double field3;

    public int field4; // Won't pass down.

    public TheChild CreateChild()
    {
        TheChild x = new TheChild();
        var fields = typeof(TheParent).GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
        foreach (var field in fields)
        {
            var attributes = field.GetCustomAttributes(typeof(PassDownAttribute), true);
            if (attributes.Length == 0) continue;
            var sourceValue = field.GetValue(this);
            var targetField = typeof(TheChild).GetField(field.Name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (targetField != null)
                targetField.SetValue(x, sourceValue);
        }
        return x;
    }
}

public class TheChild
{
    public int field1;
    public string field2;
    public double field3;
}

以及用法:

public void TestIt()
{
    TheParent p = new TheParent
    {
        field1 = 5,
        field2 = "foo",
        field3 = 4.5,
        field4 = 3
    };
    TheChild c = p.CreateChild();
    Debug.Assert(c.field1 == p.field1);
    Debug.Assert(c.field2 == p.field2);
    Debug.Assert(c.field3 == p.field3);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM