gpt4 book ai didi

c# - 将一些属性复制到新的构造函数中

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:31 25 4
gpt4 key购买 nike

我有一个包含很多属性的大类 (BigClass)。我需要创建一个仅包含其中一些属性的新类 (SmallClass)。此 SmallClass 必须使用 BigClass 中的所有重叠属性。执行此操作的最简单方法是什么,而无需像我下面那样在 SmallClass 的构造函数中手动分配所有属性:

class BigClass
{
public int A { get; }
public int B { get; }
public int C { get; }
public int D { get; }
public int E { get; }

public BigClass(int a, int b, int c, int d, int e)
{
A = a;
B = b;
C = c;
D = d;
E = e;
}
}

class SmallClass
{
public int A { get; }
public int B { get; }
public int C { get; }

public SmallClass(BigClass bigClass)
{
// I don't want to do all this manually:
A = bigClass.A;
B = bigClass.B;
C = bigClass.C;
}
}

最佳答案

创建一个辅助类:

public class Helper
{
public static void CopyItem<T>(BigClass source, T target)
{
// Need a way to rename the backing-field name to the property Name ("<A>k__BackingField" => "A")
Func<string, string> renameBackingField = key => new string(key.Skip(1).Take(key.IndexOf('>') - 1).ToArray());

// Get public source properties (change BindingFlags if you need to copy private memebers as well)
var sourceProperties = source.GetType().GetProperties().ToDictionary(item => item.Name);
// Get "missing" property setter's backing field
var targetFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField).ToDictionary(item => renameBackingField(item.Name));

// Copy properties where target name matches the source property name
foreach(var sourceProperty in sourceProperties)
{
if (targetFields.ContainsKey(sourceProperty.Key) == false)
continue; // No match. skip

var sourceValue = sourceProperty.Value.GetValue(source);
targetFields[sourceProperty.Key].SetValue(target, sourceValue);
}
}
}

然后在你的 SmallClass 构造函数中:

public SmallClass(BigClass bigClass)
{
Helper.CopyItem(bigClass, this);
}

即使您只有属性 getter ,这也应该有效。

您可以通过更改其声明使 CopyItem 适用于所有类型;

public static void CopyItem<U, T>(U source, T target)

关于c# - 将一些属性复制到新的构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com