将类型转换为类

时间:2015-08-20 19:56:04

标签: 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,但也许有办法将我的类型转换为我的目标类?

2 个答案:

答案 0 :(得分:4)

你可以用反射来做。假设所有可能的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);
    }
}

答案 1 :(得分:3)

您需要实例化该类型才能访问索引器,并且需要将其强制转换为具有索引器的内容。

您可以定义一个界面:

public interface IIndexable_String
{
    object this[string index]
    {
        get;
        set;
    }
}

将它应用到您的课程中:

public class someclass : IIndexable_String

然后实例化实例并访问索引器。

Type target = Type.GetType(DocumentType);

// Instantiate
IIndexable_String instance = (IIndexable_String)Activator.CreateInstance(target);
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
        instance[kvp.Key] = kvp.Value;                                                
    } 

当然,如果你像@dasblinkenlight那样做,你甚至不需要课堂上的魔术吸气剂和设定者,也不需要接口。