Creating a DynamicType in .NET implementing an interface but using member implementations from a base class

后端 未结 2 970
甜味超标
甜味超标 2021-01-04 07:57

I am attempting to generate a dynamic class implementing an interface, but where one or more of the members already exists in the base. I compiled the following code in C# a

2条回答
  •  有刺的猬
    2021-01-04 08:42

    The C# compiler actually emits different code for BaseType depending on whether your SubClass definition is in the same assembly or not. So if you just have this:

    interface IStuff
    {
        string Bob { get; }
    }
    
    public class BaseClass
    {
        public string Bob
        {
            get { return "Bob"; }
        }
    }
    

    and then define SubClass in another C# project, then the compiler will actually emit an explicit interface implementation within it. This is because in this case, BaseClass.get_Bob will be defined as non-virtual, which means that it can't be used to satisfy the interface's contract.

    See also Why are C# interface methods not declared abstract or virtual?, which explicitly discusses this oddity at the end of the answer.

提交回复
热议问题