开发者

Determining the Assembly of a subclass with a method in the base class

Say I have a base class in Assembly A:

public class MyBaseClass{
    public static Assembly GetMyAssembly(){
     //determine the Assembly of my subclasses
    }
}

Then I create a subclass of that class within Assembly B:

publ开发者_如何学编程ic class MySubClass : MyBaseClass {
}

From there, in my domain specific logic I invoke MySubClass.GetMyAssembly(). This logic may be in the same assembly as MySubClass OR it could be in a separate assembly. How can I determine the assembly containing the subclass that invoking the inherited method? (without overriding it) I have tried to use the different Assembly.Get*() methods in System.Reflection without any luck.


You can't. This static method really does live in the assembly that has the base type.

The best you could do is use an instance method (omit the static keyword) so the code has access to the this reference. The this.GetType() expression gives you the derived type. Its Assembly property gives you the assembly that contains the derived type.


I'd recommend, rather than using the Assembly.Get*() methods, you take a look at the Type object itself - it has some very useful properties and methods:

this.GetType().BaseType.Assembly;

If you're looking to simply get the assembly of a specific base class, you'll need to use typeof(MyBaseClass).Assembly - since your class should be aware of its inheritance chain, I don't think it will be an issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜