从 C# 中的基类获取派生类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
From base class in C#, get derived type?
提问by core
Let's say we've got these two classes:
假设我们有这两个类:
public class Derived : Base
{
public Derived(string s)
: base(s)
{ }
}
public class Base
{
protected Base(string s)
{
}
}
How can I find out from within the constructor of Base
that Derived
is the invoker? This is what I came up with:
我怎样才能从内部的构造函数中找出Base
那Derived
是调用?这就是我想出的:
public class Derived : Base
{
public Derived(string s)
: base(typeof(Derived), s)
{ }
}
public class Base
{
protected Base(Type type, string s)
{
}
}
Is there another way that doesn't require passing typeof(Derived)
, for example, some way of using reflection from within Base
's constructor?
有没有另一种不需要传递的方法typeof(Derived)
,例如,某种在Base
构造函数中使用反射的方法?
采纳答案by Juliet
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Base();
Derived1 d1 = new Derived1();
Derived2 d2 = new Derived2();
Base d3 = new Derived1();
Base d4 = new Derived2();
Console.ReadKey(true);
}
}
class Base
{
public Base()
{
Console.WriteLine("Base Constructor. Calling type: {0}", this.GetType().Name);
}
}
class Derived1 : Base { }
class Derived2 : Base { }
}
This program outputs the following:
该程序输出以下内容:
Base Constructor: Calling type: Base
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2