当类型本身未知时,我试图找出支持将整数类型(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 是什么)”。因为对象最终来自同一个来源,所以真的不可能有不匹配(短!=长)。
我为这个人为的例子道歉,这似乎是演示语法的最佳方式。
谢谢。