2

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

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();
    }
}

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

4

1 回答 1

1

您不应该通过更改Name. 相反,您应该使用专门用于此目的的属性PrivateImplementationType

memberIndexer.PrivateImplementationType = new CodeTypeReference(iface);
于 2013-05-20T20:20:32.033 回答