유형 자체를 알 수없는 경우 내장 유형 (짧은/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
"불일치가있을 수 없다"는 것은 무엇을 의미합니까? 유형을 알고 있다면 그럴 수 없습니다. 네가하지 않으면, 그럴 수있다. –
언 박싱 결과를 어떻게 사용 하시겠습니까? 언 박싱 후에 유형을 모르는 경우에는 '동적'을 추측하고 사용하는 것 외에는 아무 것도 할 수 없습니다. 언 박싱 후 유형을 알고 있다면 해당 유형을 unbox하십시오. 귀하의 예제에서 newData.IntValue는 int로만 할당 될 수 있으므로 newData.IntValue = (int) yourUnknownBoxedValue;를 수행해야합니다. 이 경우 실패하면 newData.IntValue에 할당 할 수 없습니다. 실패하지 않으면 괜찮습니다. 그래서 내가 말하는 것은 실제로입니다 : 당신이 생각하지 못한 예를 생각해보아야합니다. 왜냐하면 이것은 말이되지 않기 때문입니다. – Joren