如何从主调用者类中获取孩子的类名

我有五个班级


class Program

{

    static void Main(string[] args)

    {

        Abstract test = new Child();

        test.Exectue();

    }

}



public abstract class Abstract

{

    public void Exectue()

    {

        IStrategy strategy = new Strategy();

        strategy.GetChildClassName();

    }

}



public class Child : Abstract

{

}



public interface IStrategy

{

    void GetChildClassName();

}



public class Strategy : IStrategy

{

    public void GetChildClassName()

    {

        ???

        Console.WriteLine();

    }

}

我的问题是,如何从 Strategy 类中获取子类的名称(即测试变量的实例)。


这样做this.GetType().Name会产生“策略”,并且


var mth = new StackTrace().GetFrame(1).GetMethod();

var cls = mth.ReflectedType.Name; 

产生“摘要”,这不是我想要的。


有什么方法可以让我在不做一些奇怪的 hax 的情况下获得 Child 类的名称,比如抛出异常或传递类型。


噜噜哒
浏览 107回答 2
2回答

30秒到达战场

我不知道这是否会满足您的需求,但您可以将类的当前实例发送Abstract到Strategy类构造函数,然后获取真实类型的当前名称。或者,如果您只想发送类的名称而不是整个实例,您也可以这样做。更新代码public abstract class Abstract{    public void Execute()    {        IValidator validator = new CustomClassValidator(this.GetType().Name);        validator.Validate();    }}public interface IValidator{    void Validate();}public class CustomClassValidator : IValidator{    private string className;    public CustomClassValidator(string className)    {        this.className = className;    }    public void Validate()    {        // make some other validations and throw exceptions        Console.WriteLine(className);    }}

慕娘9325324

public interface IStrategy{    string GetChildClassName();}public class Strategy : IStrategy{    public string GetChildClassName()    {        return this.GetType().Name;    }}
打开App,查看更多内容
随时随地看视频慕课网APP