Property bag for C# class

2019-04-11 09:51发布

Accessing c# class properties like javascript language would make life a lot easier.

How we can do it in C#?

For example:

someObject["Property"]="simple string";
Console.WriteLine(someObject["FirstName"]);

4条回答
祖国的老花朵
2楼-- · 2019-04-11 10:34

dynamic keyword can be used instead

dynamic foo = ...
foo.Property = "simple string";
Console.WriteLine(foo.Property);
查看更多
Melony?
3楼-- · 2019-04-11 10:36

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-04-11 10:38

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

查看更多
做个烂人
5楼-- · 2019-04-11 10:45

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); }
    }
}
查看更多
登录 后发表回答