繁体   English   中英

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

[英]How can I get class name of a child from main caller class

我有五节课

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 类中获取 Child 类的名称(即测试变量的实例)。

执行this.GetType().Name产生“策略”,并且

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

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

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

我不知道这是否会满足您的需求,但您可以将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);
    }
}
public interface IStrategy
{
    string GetChildClassName();
}

public class Strategy : IStrategy
{
    public string GetChildClassName()
    {
        return this.GetType().Name;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM