亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從主調用者類中獲取孩子的類名

如何從主調用者類中獲取孩子的類名

C#
嚕嚕噠 2023-04-16 09:57:22
我有五個班級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 類的名稱,比如拋出異?;騻鬟f類型。
查看完整描述

2 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

我不知道這是否會滿足您的需求,但您可以將類的當前實例發送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);

    }

}


查看完整回答
反對 回復 2023-04-16
?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

public interface IStrategy

{

    string GetChildClassName();

}


public class Strategy : IStrategy

{

    public string GetChildClassName()

    {

        return this.GetType().Name;

    }

}


查看完整回答
反對 回復 2023-04-16
  • 2 回答
  • 0 關注
  • 134 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號