简体   繁体   中英

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

I have five classes

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();
    }
}

My question is, how can I get the name of a Child class (the one that is the instance of test variable) from Strategy class.

Doing this.GetType().Name yields "Strategy", and

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

yields "Abstract" which is not what i want.

Is there any way that I can get the name of a Child class without doing some weird haxs, like throwing exception or passing type.

I don't know if this will satisfy your needs but you can send the current instance of the Abstract class to the Strategy class constructor and then get the current name of real type.

Or if you want to send only the name of the class instead of the whole instance you can do that also.

Update to the code

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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