我如何从主叫方 class 获得 child 的 class 姓名
How can I get class name of a child from main caller class
我有五个 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();
}
}
我的问题是,如何从 Strategy class.[=16= 中获取 Child class(作为测试变量实例的那个)的名称]
执行 this.GetType().Name
会产生 "Strategy",并且
var mth = new StackTrace().GetFrame(1).GetMethod();
var cls = mth.ReflectedType.Name;
产量 "Abstract" 这不是我想要的。
有什么方法可以让我获得 Child class 的名称,而不用做一些奇怪的 hax,比如抛出异常或传递类型。
public interface IStrategy
{
string GetChildClassName();
}
public class Strategy : IStrategy``
{
public string GetChildClassName()
{
return this.GetType().Name;
}
}
我不知道这是否能满足您的需求,但您可以将 Abstract
class 的当前实例发送到 Strategy
class 构造函数,然后获取真实类型的当前名称。
或者如果您只想发送 class 的名称而不是整个实例,您也可以这样做。
代码更新
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);
}
}
我有五个 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();
}
}
我的问题是,如何从 Strategy class.[=16= 中获取 Child class(作为测试变量实例的那个)的名称]
执行 this.GetType().Name
会产生 "Strategy",并且
var mth = new StackTrace().GetFrame(1).GetMethod();
var cls = mth.ReflectedType.Name;
产量 "Abstract" 这不是我想要的。
有什么方法可以让我获得 Child class 的名称,而不用做一些奇怪的 hax,比如抛出异常或传递类型。
public interface IStrategy
{
string GetChildClassName();
}
public class Strategy : IStrategy``
{
public string GetChildClassName()
{
return this.GetType().Name;
}
}
我不知道这是否能满足您的需求,但您可以将 Abstract
class 的当前实例发送到 Strategy
class 构造函数,然后获取真实类型的当前名称。
或者如果您只想发送 class 的名称而不是整个实例,您也可以这样做。
代码更新
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);
}
}