如何将Object转换为实际类型并进行转换?

时间:2016-05-03 01:48:35

标签: c#

如何将对象数量放入_StoredStock?数量是一个对象,我发现很难将其转换为int以将值放入_StoredStock

class EachStock: Stock
{

    public override void bookStock(Quantity quantity)
    {
        if (quantity.GetType() == typeof(EachStockQuantity))
        {
            //How to placethe object quantity into a _BookedStock
            // the quantity is an object which I find it hard to convert it to int for _StoredStock
        }
    }

}

3 个答案:

答案 0 :(得分:1)

您尝试在整数变量中存储类实例。我认为问题的一部分是参数名称具有误导性,因为它不是数量,而是具有数量属性的类。

访问您需要的媒体资源,在这种情况下Quantity

public override void AdjustStock(StockQuantity stockQty)
{
    if (stockQty.GetType() == typeof(DiscreteStockQuantity))
        _StoredStock = ((DiscreteStockQuantity)stockQty).Quantity;
}

或者,可能稍微更具可读性(但这是一个意见问题):

public override void AdjustStock(StockQuantity stockQty)
{
    var discStockQty = stockQty as DiscreteStockQuantity;

    if (discStockQty != null)
        _StoredStock = discStockQty.Quantity;
}

答案 1 :(得分:0)

有多种方法可以了解类型并进行实际转换。

这是一个懒惰的例子:

class Program
{
    static void Main(string[] args)
    {

        object obj = new Foo();


        Type objType = obj.GetType();

        if(objType == typeof(Foo))
        {
            var foobar = (Foo)obj;

            Console.WriteLine(foobar.Bar);
        }
        else if(objType == typeof(int))
        {
            // Do something
        }
        else
        {
            // Do something
        }

        // If you are brave enough you can use dynamic

        dynamic bar = obj;

        Console.WriteLine(bar.Bar);

        Console.ReadLine();
    }
}

class Foo
{
    public string Bar { get; set; }

    public Foo()
    {
        Bar = "FooBar";
    }
}

输出:

FooBar
FooBar

更新

以下是与您的问题类似的示例

class Program
{
    static void Main(string[] args)
    {
        int i = FooBar(new Foo());

        Console.WriteLine(i);

        Console.ReadLine();
    }

    public static int FooBar(FooBase fooBase)
    {
        int val = -1;

        Type type = fooBase.GetType();

        if(type == typeof(Foo))
        {
            Foo foo = (Foo)fooBase;

            val = foo.Bar;
        }
        else
        {
            // Do something
        }

        return val;
    }
}

class Foo : FooBase
{
    public int Bar { get; set; }

    public Foo()
    {
        Bar = 999;
    }
}

class FooBase
{

}

输出:

999

答案 2 :(得分:0)

试试这个:

dM[,  time :=  unique(gsub("\\D+", "", names(data)[-1]))[time]][]