Property bag for C# class

偶尔善良 提交于 2019-12-04 12:02:08
r.zarei

Here is how you can enable property-bag-like functionality in your classes by adding a few lines of code:

partial class SomeClass
{
    private static readonly PropertyDescriptorCollection LogProps = TypeDescriptor.GetProperties(typeof(SomeClass));

    public object this[string propertyName]
    {
        get { return LogProps[propertyName].GetValue(this); }
        set { LogProps[propertyName].SetValue(this, value); }
    }
}

This code would work

dynamic user= new ExpandoObject();
user.name = "Anonymous";
user.id=1234
user.address="12 broad way"
user.State="NY"

import System.Dynamic namespace.

dynamic keyword can be used instead

dynamic foo = ...
foo.Property = "simple string";
Console.WriteLine(foo.Property);

You could derive every single class from Dictionary<string, object>. But then, you could simply take JavaScript instead of misusing C#.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!