如何使用CodeDOM创建显式接口声明索引属性

时间:2013-05-20 19:22:56

标签: c# interface indexing codedom explicit-interface

我正在尝试创建一个显式的接口声明索引属性。例如:

public interface IFoo
{
    int this[int i]
}

public abstract class Foo : IFoo
{
    int IFoo.this[int i]
}

我编写了以下代码来执行此操作(这适用于普通索引属性,但不适用于显式接口声明索引属性):

var iface = typeof(IFoo);
var method = iface.GetMethod("Item"); // get the indexer

CodeMemberProperty memberIndexer = new CodeMemberProperty();

memberIndexer.Name = iface.Name + ".Item";

memberIndexer.Type = new CodeTypeReference(method.ReturnType.Name);
memberIndexer.HasSet = true;
memberIndexer.HasGet = true;

foreach (var param in method.GetParameters())
{
    memberIndexer.Parameters.Add(
        new CodeParameterDeclarationExpression(
        new CodeTypeReference(param.ParameterType), param.Name));
}

// Explicit interface declaration cannot have any modifiers
memberIndexer.Attributes = ~MemberAttributes.Private;

// add to both set/get to NotImplementedException
var exceptionStatement = new CodeThrowExceptionStatement(
    new CodeObjectCreateExpression(
        new CodeTypeReference(typeof(System.NotImplementedException)),
        new CodeExpression[] { }));
memberIndexer.GetStatements.Add(exceptionStatement);                  
memberIndexer.SetStatements.Add(exceptionStatement);

TargetClass.Members.Add(memberIndexer);

但是,这会生成以下代码:

int IFoo.Item
{
    get
    {
        throw new System.NotImplementedException();
    }
    set
    {
        throw new System.NotImplementedException();
    }
}

有关如何正确执行此操作的任何想法?

1 个答案:

答案 0 :(得分:1)

您不应该通过更改Name来执行此操作。相反,您应该使用完全用于此目的的属性:PrivateImplementationType

memberIndexer.PrivateImplementationType = new CodeTypeReference(iface);