简体   繁体   English

在运行时动态创建和设置类的成员/属性

[英]Dynamically create and set members/properties of class at runtime

How can I create and set members/properties of a class dynamically at runtime. 如何在运行时动态创建和设置类的成员/属性。

Ref: http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember(v=vs.110).aspx 参考: http//msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember( v= vs.110).aspx

I tried to modify the idea to suit my requirements but unable to do it. 我试图修改这个想法以满足我的要求,但无法做到。

I am required to set the class members at runtime, means I would fetch the Key and Value from the database and my class will be completely dynamic with no members defined before runtime, but all of them is fetched from database during runtime. 我需要在运行时设置类成员,这意味着我将从数据库中获取KeyValue ,并且我的类将是完全动态的,在运行时之前没有成员定义,但所有这些都是在运行时从数据库中获取的。

So here goes my code (Taken from MSDN): 所以这里是我的代码(取自MSDN):

public class DynamicObjDictionary : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary = new Dictionary<string, object>();
    public int Count
    {
        get{return dictionary.Count;}
    }

public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name.ToLower();
        return dynDict.TryGetValue(name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dynDict[binder.Name.ToLower()] = value;
        return true;
    }
 }
}

The code that initializes and defines the members/properties of the class 初始化和定义类的成员/属性的代码

dynamic DynObj = new DynamicObjDictionary();
        DataSet ds = new DataSet();
        ds = GetObjectProperties() // returns dataset having the properties as key and value pair;
        if (ds.Tables["PropTable"].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables["PropTable"].Rows)
            {
                string KeyName = dr["KeyName"].ToString();
                string ValueName= dr["ValueName"].ToString();
                //---I want that in place of fldName the actual value from dr is added to the class - currently it returns DynObj.KeyName only.
                DynObj.KeyName = ValueName;
                // Means if current dr["KeyName"].ToString() has "Property1"
                // And dr["ValueName"].ToString() has "PropertyValue"
                // The DynObj should be like DynObj.Property1 = "PropertyValue" 
            }
        }

And another problem is that I want all the properties to be set after the above initialization so that I can access them like a class object that is hard-coded. 另一个问题是我希望在上面的初始化之后设置所有属性,以便我可以像硬编码的类对象一样访问它们。 Current code only retails the last property ie the value of the last row of the dataset. 当前代码仅零售最后一个属性,即数据集的最后一行的值。

Either add a dictionary-based API, or use an implementation that already has it. 添加基于字典的API,或使用已有它的实现。 Frankly ExpandoObject would work fine, and has an IDictionary<string,object> API built in. 坦率地说ExpandoObject可以正常工作,并且内置了IDictionary<string,object> API。

var obj = new ExpandoObject();
DataSet ds = GetObjectProperties() // returns dataset having the properties as key and value pair;
if (ds.Tables["PropTable"].Rows.Count > 0)
{
    foreach (DataRow dr in ds.Tables["PropTable"].Rows)
    {
        string KeyName = dr["KeyName"].ToString();
        string ValueName= dr["ValueName"].ToString();
        obj[KeyName] = ValueName;
    }
}
dynamic DynObj = obj;
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM