如果我有一个这样定义的类:
public class className
{
public object this[string propertyName]
{
get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
}
public string Foo{ get; set; }
public string Bar { get; set; }
我当然可以像这样设置和获取值:
className d = new className();
d["Foo"]="abcd" // set
string s = (string)f["Bar"];
(感谢 Eduardo Cuomo 的回答 here )
但我真正想做的是:
Type target = Type.GetType(DocumentType);
// loop through list of key-value pairs and populate the data class defined in target object Type
foreach (Dictionary<string, string> PQList in LPQReq)
{
foreach (KeyValuePair<string, string> kvp in PQList)
{
// populate the member in the data class with the value from the MQ String
target[kvp.Key] = kvp.Value;
}
但这不会编译为 Cannot apply indexing with [] to an expression of type 'System.Type'
那我该怎么做呢?
我当然可以使用 dynamic
,但也许有一种方法可以将我的类型转换为我的目标类?
最佳答案
你可以通过反射(reflection)来做到这一点。假设所有可能的 DocumentType
都有一个无参数的构造函数,您可以这样做:
// Get the type (this comes from your example)
Type target = Type.GetType(DocumentType);
// Create an instance (that's the important part that was missing)
object instance = Activator.CreateInstance(target);
foreach (Dictionary<string, string> PQList in LPQReq) {
foreach (KeyValuePair<string, string> kvp in PQList) {
// This code again comes from your example,
// except propertyName is kvp.Key and value is kvp.Value
target.GetProperty(kvp.Key).SetValue(instance, kvp.Value, null);
}
}
关于c# - 将类型转换为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127193/