有没有办法在c#中动态创建属性?

时间:2013-02-01 11:33:20

标签: c# properties

public class UserDetails
    {
        public string UserID { get; set; }

        public string UserName { get; set; }
    }

这里我想动态添加属性。 类型属性名称会动态更改,我希望创建属性值。

3 个答案:

答案 0 :(得分:1)

这似乎有效,但需要强制转换才能达到“灵活”的属性。

UserDetails

public class UserDetails
{
    private dynamic _internal;

    public static implicit operator System.Dynamic.ExpandoObject(UserDetails details)
    {
        return details._internal;
    }

    public UserDetails()
    {
        _internal = new System.Dynamic.ExpandoObject();
    }

    public string UserID 
    { 
        get
        {
            return _internal.UserID;
        }
        set
        {
            _internal.UserID = value;
        }
    }

    public string UserName
    { 
        get
        {
            return _internal.UserName;
        }
        set
        {
            _internal.UserName = value;
        }
    }
}

使用班级

UserDetails user = new UserDetails();
user.UserName = "bill";
user.UserID = "1";

dynamic dynamicUser = (System.Dynamic.ExpandoObject)user;
dynamicUser.newMember = "check this out!";

Console.WriteLine(user.UserName);
Console.WriteLine(user.UserID);
Console.WriteLine(dynamicUser.UserName);
Console.WriteLine(dynamicUser.UserID);
Console.WriteLine(dynamicUser.newMember);

答案 1 :(得分:0)

是的,但这很复杂。 检查实施ICustomTypeDescriptor。如果您使基类实现它,您将能够动态添加属性。网上有教程,在网上搜索界面。

第二件事可以是使用ExpandoObject 通过这种方式,您无法从基类继承,但实现起来要简单得多。

答案 2 :(得分:0)

您可能真正需要的只是一个“Property Bag”,即一个无序容器,您可以在其中插入名称/值对,其中名称是字符串,值是任何类型的对象。

PropertyBag有许多在线实现;这是一个快速而肮脏的人,我把它作为一个例子:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;

namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            var properties = new PropertyBag();

            properties["Colour"]   = Color.Red;
            properties["π"]        = Math.PI;
            properties["UserId"]   = "My User ID";
            properties["UserName"] = "Matthew";

            // Enumerate all properties.

            foreach (var property in properties)
            {
                Console.WriteLine(property.Key + " = " + property.Value);
            }

            // Check if property exists:

            if (properties["UserName"] != null)
            {
                Console.WriteLine("[UserName] exists.");
            }

            // Get a property:

            double π = (double)properties["π"];
            Console.WriteLine("Pi = " + π);
        }
    }

    public sealed class PropertyBag: IEnumerable<KeyValuePair<string, object>>
    {
        public object this[string propertyName]
        {
            get
            {
                if (propertyName == null)
                {
                    throw new ArgumentNullException("propertyName");
                }

                if (_dict.ContainsKey(propertyName))
                {
                    return _dict[propertyName];
                }
                else
                {
                    return null;
                }
            }

            set
            {
                if (propertyName == null)
                {
                    throw new ArgumentNullException("propertyName");
                }

                _dict[propertyName] = value;
            }
        }

        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
        {
            return _dict.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private readonly Dictionary<string, object> _dict = new Dictionary<string, object>();
    }
}