我试图找出当它的类型本身是未知的时候支持拆箱整型(short/int/long)到其内在类型的语法。拆箱到未知类型
下面是一个说明的概念的完全人为的例子:
// Just a simple container that returns values as objects
struct DataStruct
{
public short ShortVale;
public int IntValue;
public long LongValue;
public object GetBoxedShortValue() { return ShortVale; }
public object GetBoxedIntValue() { return IntValue; }
public object GetBoxedLongValue() { return LongValue; }
}
static void Main(string[] args)
{
DataStruct data;
// Initialize data - any value will do
data.LongValue = data.IntValue = data.ShortVale = 42;
DataStruct newData;
// This works if you know the type you are expecting!
newData.ShortVale = (short)data.GetBoxedShortValue();
newData.IntValue = (int)data.GetBoxedIntValue();
newData.LongValue = (long)data.GetBoxedLongValue();
// But what about when you don't know?
newData.ShortVale = data.GetBoxedShortValue(); // error
newData.IntValue = data.GetBoxedIntValue(); // error
newData.LongValue = data.GetBoxedLongValue(); // error
}
在每种情况下,积分的类型是一致的,所以应该有某种形式的句法,说:“该对象包含一个简单的类型的X,返回X(即使我不知道X是什么)“。因为对象最终来自同一个来源,所以实际上不会有不匹配(short!= long)。
我为这个人为的例子表示歉意,它似乎是展示语法的最好方式。
谢谢。
所有的你'GetBoxed'方法返回'LongValue'。错字? – unholysampler 2010-05-19 20:21:22
你是什么意思“不可能有不匹配”?如果你知道这个类型,那么就不会有;如果你不这样做,那么可以。 – 2010-05-19 20:21:49
你想如何使用拆箱的结果?如果拆箱后你不知道这种类型,那么你就无法做任何事情(除了猜测和使用'dynamic')。如果您在拆箱后知道该类型,请将其取消装箱。在你的榜样,你知道newData.IntValue只能与一个int被分配,让你_have_做'newData.IntValue =(int)的yourUnknownBoxedValue;'。如果这样做失败,则不能将其分配给newData.IntValue。如果它没有失败,那么你很好。 所以我说的是真的:你应该想出一个没有人为的例子,因为这没有意义。 – Joren 2010-05-19 20:39:50