积极答复者
如何在静态方法中获取类的反射

问题
-
如何在基类的静态方法中确定是那个派生类调用了这个静态方法?
例如:
class BaseClass { public static void StaticMethod() { Type type = /*某种方法*/; } } class classA:BaseClass { } class classB:BaseClass { }
如何在调用classA.StaticMethod()时,StaticMethod中type的值等于typeof(classA),而在调用classB.StaticMethod()时,type的值等于typeof(classB)?
希望各位大神不吝赐教!!
答案
-
建议你直接判断即可:
namespace CSharp { class BaseClass { public static void StaticMethod(Type t) { if (typeof(BaseClass).IsAssignableFrom(t)) { Console.WriteLine("是子类:" + t); } else { Console.WriteLine("不是子类……"); } } } class classA : BaseClass { } class classB : BaseClass { } class Program { static void Main(string[] args) { classA.StaticMethod(typeof(classA)); } } }
If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats- 已标记为答案 ykm31305750 2013年3月12日 14:01
全部回复
-
建议你直接判断即可:
namespace CSharp { class BaseClass { public static void StaticMethod(Type t) { if (typeof(BaseClass).IsAssignableFrom(t)) { Console.WriteLine("是子类:" + t); } else { Console.WriteLine("不是子类……"); } } } class classA : BaseClass { } class classB : BaseClass { } class Program { static void Main(string[] args) { classA.StaticMethod(typeof(classA)); } } }
If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats- 已标记为答案 ykm31305750 2013年3月12日 14:01
-
基类是不会知道子类的信息的。
你可以在子类中重写这个方法,然后返回子类自己的信息。
Mike Feng
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help.