【问题标题】:c# codedom create property which returns a dictionary elementc# codedom create 属性,它返回一个字典元素
【发布时间】:2017-04-27 07:54:52
【问题描述】:

要在 codedom 中创建带有支持字段的属性,我们可以使用如下构造:

CodeMemberProperty property = new CodeMemberProperty;
           property.GetStatements.Add(
               new CodeMethodReturnStatement(
                   new CodeFieldReferenceExpression(
                       new CodeThisReferenceExpression(),
                                                      fieldName)));

但是“CodeMethodReturnStatement”内部的构造必须是这样的结果:

public string SomeProp { get { return _someDict[_someKey]; } }

地点:

_someDict = new Dictionary<string, string>();
_someKey = "someKey";

_someDict 和 _someKey 是同一个生成类的成员。

【问题讨论】:

  • 我认为你需要 CodeIndexerExpression 类。
  • 您不应编辑您的问题以包含答案。相反,您应该将其作为答案发布,然后您可以接受它。

标签: c# dictionary properties codedom


【解决方案1】:

感谢评论,我会这样解决问题:

CodeIndexerExpression indexerExpression =
            new CodeIndexerExpression(
                new CodeFieldReferenceExpression(
                    new CodeTypeReferenceExpression(typeof(Class1)), 
                    "dict"),
                new CodeFieldReferenceExpression(
                    new CodeTypeReferenceExpression(typeof(Class1)), 
                    "key"));

请注意,我的键字段和字典字段是静态的,但对于局部变量的想法是相同的。 只需使用 CodeThisReferenceExpression 代替 CodeTypeReferenceExpression。

    public static string Prop
    {
        get
        {
            return Class1.dict[Class1.key];
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多