有没有办法在C#中为对象添加键/值语法?

use*_*234 0 c# extension-methods

我有一个叫做CottonCandy的物品.CottonCandy有一些属性:

  • 体积
  • TotalSugar
  • 颜色

如果我可以向CottonCandy添加一些内容以便我可以检索这样的属性,那将是多么伟大的事情:

var colors = cottonCandy["Colors"];
Run Code Online (Sandbox Code Playgroud)

从阅读本文看起来你可以获得价值:

cottonCandy.GetType().GetProperty("Colors").GetValue(cottonCandy, null);
Run Code Online (Sandbox Code Playgroud)

你可以轻松地将其包装在一个方法中:

var colors = cottonCandy.GetPropertyValue("Colors");
Run Code Online (Sandbox Code Playgroud)

但我真的更喜欢键/值语法cottonCandy["Colors"].有没有办法让这种情况发生?

rat*_*per 6

实际上有一种方法.您可以使用索引器.但是您需要在类型中使用相同的字段类型或框值object.

class CottonCandy
{
    private int Mass { get; set; }
    private int Volume { get; set; }
    private int TotalSugar { get; set; }
    private int Colors { get; set; }

    public int this[string field]
    {
        get
        {
            PropertyInfo propertyInfo = typeof(CottonCandy).GetProperty(field);
            if(propertyInfo == null)
                throw new ArgumentException("Invalid field");
            return (int)propertyInfo.GetValue(this);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)