泛型:如何检查T的确切类型,没有T的对象

CSh*_*oob 10 c# generics

如何在没有T的对象的情况下检查/评估T的确切类型.我知道我的问题可能令人困惑,但请考虑一下......

 public abstract class Business
    {
        public abstract string GetBusinessName();
    }

    public class Casino : Business  
    {
        public override string GetBusinessName()
        {
            return "Casino Corp";
        }
    }

    public class DrugStore : Business 
    {
        public override string GetBusinessName()
        {
            return "DrugStore business";
        }
    }


    public class BusinessManager<T> where T : Business
    {
        private Casino _casino;
        private DrugStore _drugStore;

        public string ShowBusinessName()
        {
            string businessName;
            if (T == Casino) // Error: How can I check the type?
            {
                _casino = new Casino();
                businessName = _casino.GetBusinessName();
            }
            else if (T == DrugStore) // Error: How can I check the type?
            {
                _drugStore = new DrugStore();
                businessName = _drugStore.GetBusinessName();
            }

            return businessName;

        }
    }
Run Code Online (Sandbox Code Playgroud)

我只是想在客户端上有这样的东西.

    protected void Page_Load(object sender, EventArgs e)
    {
        var businessManager = new BusinessManager<Casino>();
        Response.Write(businessManager.ShowBusinessName());

        businessManager = new BusinessManager<DrugStore>();
        Response.Write(businessManager.ShowBusinessName());
    }
Run Code Online (Sandbox Code Playgroud)

请注意,当我调用BusinessManager时,我实际上没有为Casino和Drugstore创建实际对象,我只是将其作为类的泛型类型约束传递.我只需要知道我正在传递什么类型的BusinessManager来知道要实例化的Type究竟是什么.谢谢...

PS:我不想为Casino和Drugstore创建单独的特定BusinessManager.

您还可以对设计发表评论..谢谢..

附加:如果类Casino和DrugStore是抽象类=如果=)

jas*_*son 12

你可以写

if(typeof(T) == typeof(Casino))
Run Code Online (Sandbox Code Playgroud)

但实际上这种逻辑是一种代码味道.

这是解决这个问题的一种方法:

public class BusinessManager<T> where T : Business, new() {
    private readonly T business;
    public BusinessManager() {
        business = new T();
    }
}
Run Code Online (Sandbox Code Playgroud)

但我个人更喜欢

public class BusinessManager<T> where T : Business {
    private readonly T business;
    public BusinessManager(T business) {
        this.business = business;
    }

    public string GetBusinessName() { 
        return this.business.GetBusinessName();
    }
}
Run Code Online (Sandbox Code Playgroud)


Alb*_*nbo 9

你应该做

public class BusinessManager<T> where T : Business, new()
...

T _business = new T();
string businessName = _business.GetBusinessName();
return businessName;
Run Code Online (Sandbox Code Playgroud)