获取基类类型

时间:2014-11-08 21:58:24

标签: c# class types

我相信邮政的名字与问题没什么关系,但我无法表达更好

我有以下课程:

public class BuyAction
{
    public Deals Deals{ get; set; }
}

public class SellAction
{
    public Deals Deals { get; set; }
}

public class Deals
{
    public int GetDealValueByType(object obj)
    {
        if (obj.GetType() == typeof (BuyAction))
        {
            return 1;
        }
        if (obj.GetType() == typeof (SellAction))
        {
            return 2;
        }
        return 0;
    }
}

    static void Main(string[] args)
    {
        var action = new BuyAction();
        var dealValue = action.Deals.GetDealValueByType(action);
    }

我的问题: 如何在不将参数传递给方法“GetDealValueByType”的情况下返回dealValue?

2 个答案:

答案 0 :(得分:1)

尝试使用泛型:

public class BaseAction{} 

public class BuyAction : BaseAction
{
    public int Value { get{ return 1; }} 
}

public class SellAction : BaseAction
{
    public int Value { get{ return 2; }}
}

public class Deals<T> where T : BaseAction,  new() 
{
    public int GetDealValue()
    {
        var data = new T();
        return data.Value;
    }
}

然后将其用作:

var deal1 = new Deals<BuyAction>();
var value1 = deal1.GetDealValue();

var deal2 = new Deals<SellAction>();
var value2 = deal2.GetDealValue();

答案 1 :(得分:0)

在您编写的代码中,Deals并不了解BuyActionSellAction的存在,因此无法知道什么类正在使用它。为了做到这一点,你应该以某种方式与它沟通。这是一种方法:

public abstract class BaseAction
{
    private Deals _deals;
    public Deals Deals 
    {
        get
        {
            if (_deals == null)
                 // this = BuyAction or SellAction, never BaseAction because it's abstract
                _deals = new Deals(this);
            return _deals;
        }
        set
        {
            _deals = value;
        }
    }

}

public class BuyAction : BaseAction { }
public class SellAction : BaseAction { }

public class Deals
{
    private BaseAction _callerAction;
    public Deals(BaseAction caller)
    {
        this._callerAction = caller;
    }

    public int GetDealValueByType()
    {
        if (this._callerAction is BuyAction)
        {
            return 1;
        }
        if (this._callerAction is SellAction)
        {
            return 2;
        }
        return 0;
    }
}

public static void Main(string[] args)
{
    BaseAction action = new BuyAction();
    int dealValue = action.Deals.GetDealValueByType();
    // Prints 1
    Console.WriteLine(dealValue);

    action = new SellAction();
    dealValue = action.Deals.GetDealValueByType();
    // Prints 2
    Console.WriteLine(dealValue);
}

如您所见,现在Deals类需要一个BaseAction类来实例化它。这种方式现在你强制类知道谁在使用它,然后你可以以面向对象的方式做出决定。

最后,你得到的不是基类,它是调用者或容器类。在您的示例中,唯一的基类是object