c# - 将类型转换为类

标签 c# reflection indexing

如果我有一个这样定义的类:

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/

相关文章:

C# - 单例模式

c# - 如何在运行时为反射方法创建委托(delegate)

.net - 在运行时创建一个类并在.Net 中使用它?

sql - 非聚集(非 PK)索引是否需要包含聚集(PK)列?

c# - 使用 ITextSharp 提取和更新现有 PDF 中的链接

c# - basic 中 string$ 的 C# 等价物是什么

javascript - 根据单击的链接显示不同的选项卡

c# - 使用泛型类中定义的泛型参数调用非泛型方法

python-3.x - 绘图时的 Matplotlib 索引错误

php - 如何使用索引提高查询性能?