C# 如何从主调用方类中获取子类的类名

C# 如何从主调用方类中获取子类的类名,c#,inheritance,system.reflection,C#,Inheritance,System.reflection,我有五节课 class Program { static void Main(string[] args) { Abstract test = new Child(); test.Exectue(); } } public abstract class Abstract { public void Exectue() { IStrategy strategy = new Strategy();

我有五节课

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
会产生“策略”,并且

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


有没有办法不用做一些奇怪的hax就能得到一个子类的名字,例如抛出异常或传递类型。

我不知道这是否能满足您的需要,但您可以将
抽象类的当前实例发送到
策略
类构造函数,然后获取实际类型的当前名称

public interface IStrategy
    {
      string GetChildClassName();
    }

public class Strategy : IStrategy``
    {
public string GetChildClassName()
     {
    return this.GetType().Name;
     }
    }
或者,如果只想发送类的名称而不是整个实例,也可以这样做

更新代码

公共抽象类抽象
{
public void Execute()
{
IValidator validator=新的CustomClassValidator(this.GetType().Name);
validator.Validate();
}
}
公共接口IValidator
{
void Validate();
}
公共类CustomClassValidator:IValidator
{
私有字符串类名;
公共CustomClassValidator(字符串类名称)
{
this.className=className;
}
public void Validate()
{
//进行一些其他验证并抛出异常
Console.WriteLine(类名);
}
}

您是否将使用
StackTrace
的尝试视为一种奇怪的黑客行为?
StackTrace
方法也会返回“抽象”。不,因为我知道抽象和策略之间不会有中间人。你必须使用
Strategy
类来获取类型,还是可以使用多态性?是的,我必须使用Strategy类。在我的真实场景中,strategy类负责验证,在这个验证类中,我抛出包含无效子类名称的异常。您没有嵌套类的示例。正如我前面所说,这种方法返回“strategy”。子类的名称应该封装在Strategy类中,因为我只需要在那里使用它。concern的分离我确实希望避免将类的整个实例传递给validate方法(或任何与验证无关的方法),它打破了关注点的分离,因为我的验证依赖于传递调用方类的实例,当我只需要名称时有点过分了。是的,我当然可以传递名称,但是为了验证目的获取名称不应该是抽象类的责任,验证应该能够自己获取名称,
验证程序的责任应该是验证类的类型。其他人应该负责将类型发送到
验证器
,在这种情况下,它是
抽象类。通过这种方法,我们可以保护代码不受未来更改的影响,并且可以在其他地方使用
验证器。我对代码做了一些更改。我试图避免细节,因为我必须处理Dynamics CRM,这将使事情变得更加复杂,但是。我的
验证器
不验证类的类型。我只需要类的类型来创建适当的异常消息。这样其他的程序员就会知道他失败了,他必须去那个特定的类并做一些更改。在我们的代码库中,所有具有业务逻辑的类都继承自
Abstract
。事实上,
Validator
不会在其他任何地方使用,因为所有“重要”类都已经通过
Abstract
隐式使用了它。如果我要进行一些需要类或实例名称的验证,我完全同意您的解决方案。但在我的情况下,我只需要它作为异常消息。我希望我们可以从reflection中阅读到这些信息。我认为使用reflection将在将来给您带来问题,因为您正在使
验证器
了解
抽象类。对于其他方法,
验证器只做他需要做的工作。他不需要知道如何获取封装他的类的名称。他的工作只是验证一些东西,并抛出特定的消息,或者在一切正常的情况下返回结果。
public interface IStrategy
    {
      string GetChildClassName();
    }

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