您可以使用反射來做到這一點,但速度會很慢。以下是一個演示的主要的一個小程序(你可以編譯和運行它):
using System;
using System.Collections.Generic;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var log = new XmlLog();
var values = new Dictionary<string, string> { { "Hello", "1" }, { "World", "2" } };
foreach (var methodInfo in typeof(XmlLog).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
methodInfo.SetValue(log, values[methodInfo.Name]);
}
Console.WriteLine(log.Hello);
Console.WriteLine(log.World);
}
class XmlLog
{
public string Hello { get; set; }
public string World { get; set; }
}
}
這可以通過使用代碼生成速度更快。您有幾個選項,如:
- 對XmlLog類型使用反射並生成將與您的應用程序一起編譯的C#代碼。
- 使用Reflection來構建一個設置XmlLog屬性的表達式,然後在運行時將其編譯爲Func或Action。
來源
2013-07-03 23:23:06
Ran
我編輯了您的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –
重複[在C#中如何動態指定對象的成員,如obj \ [「abc」\]](http://stackoverflow.com/questions/5716766/in-c-sharp-how-to-dynamically -specify-a-object-like-objabc-in-p) –