2 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
我認(rèn)為您的原始版本最終會(huì)將值設(shè)置為“太深一層”。
我認(rèn)為遞歸模式更容易遵循,并且需要更少的代碼。這是我整理的一個(gè)快速版本,適用于簡(jiǎn)單的測(cè)試用例。
有幾個(gè)優(yōu)化機(jī)會(huì)(在遞歸調(diào)用中重建字符串)和邊緣情況(如null檢查),我現(xiàn)在沒有時(shí)間處理,但我認(rèn)為它們不會(huì)太難添加。
public void SetProperty(object target, string property, object setTo)
{
var parts = property.Split('.');
var prop = target.GetType().GetProperty(parts[0]);
if (parts.Length == 1)
{
// last property
prop.SetValue(target, setTo, null);
}
else
{
// Not at the end, go recursive
var value = prop.GetValue(target);
SetProperty(value, string.Join(".", parts.Skip(1)), setTo);
}
}
這是一個(gè) LINQPad 演示,展示了它的實(shí)際效果:
void Main()
{
var value = new A();
Debug.WriteLine("Original value:");
value.Dump();
Debug.WriteLine("Changed value:");
SetProperty(value, "B.C.D","changed!");
value.Dump();
}
public void SetProperty(object target, string property, object setTo)
{...}
public class A
{
public B B { get; set; } = new B();
}
public class B
{
public C C { get; set; } = new C();
}
public class C
{
public string D { get; set; } = "test";
}
它產(chǎn)生以下結(jié)果:

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
我想完成答案Bradley Uffner
public void SetProperty (object target, string property, object setTo)
{
var parts = property.Split ('.');
// if target object is List and target object no end target -
// we need cast to IList and get value by index
if (target.GetType ().Namespace == "System.Collections.Generic"
&& parts.Length != 1)
{
var targetList = (IList) target;
var value = targetList[int.Parse (parts.First ())];
SetProperty (value, string.Join (".", parts.Skip (1)), setTo);
}
else
{
var prop = target.GetType ().GetProperty (parts[0]);
if (parts.Length == 1)
{
// last property
prop.SetValue (target, setTo, null);
}
else
{
// Not at the end, go recursive
var value = prop.GetValue (target);
SetProperty (value, string.Join (".", parts.Skip (1)), setTo);
}
}
}
- 2 回答
- 0 關(guān)注
- 145 瀏覽
添加回答
舉報(bào)