[英]C#: run-time datatype conversion
這是我第一次自己使用StackOverflow。 我之前在這里找到了許多問題的答案,所以我想我會嘗試自己問一些問題。
我正在做一個小項目,我現在有點卡住了。 我知道如何解決我的問題 - 而不是我希望它解決的方式。
該項目包括一個NBT解析器,我決定自己寫,因為它將用於或多或少的自定義NBT文件變體,雖然核心原則是相同的:二進制數據流與特定種類的預定義“關鍵字”標簽。 我決定嘗試為所有不同類型的標簽創建一個類,因為標簽的結構非常相似 - 它們都包含類型和有效負載。 這就是我被困的地方。 我希望有效負載具有特定類型,當隱式執行顯式轉換時,會拋出錯誤。
我能想到的最好的方法是制作Object類型或動態的有效負載,但這樣可以隱式地完成所有轉換:
Int64 L = 90000;
Int16 S = 90;
dynamic Payload; // Whatever is assigned to this next will be accepted
Payload = L; // This fine
Payload = S; // Still fine, a short can be implicitly converted to a long
Payload = "test"; // I want it to throw an exception here because the value assigned to Payload cannot be implicitly cast to Int64 (explicit casting is ok)
有沒有辦法做到這一點? 我想通過某種方式告訴C#從現在開始解決它,即使Payload是動態的,如果指定的值不能隱式轉換為當前值的類型,它將拋出異常 - 當然,除非它完成明確。
我願意接受其他方法來實現這一目標,但我想避免這樣的事情:
public dynamic Payload
{
set
{
if(value is ... && Payload is ...) { // Using value.GetType() and Payload.GetType() doesn't make any difference for me, it's still ugly
... // this is ok
} else if(...) {
... // this is not ok, throw an exception
}
... ... ...
}
}
你考慮過使用泛型嗎? 這將自動為您提供編譯時檢查允許的轉換。
class GenericTag<T>
{
public GenericTag(T payload)
{
this.Payload = payload;
}
public T Payload { set; get; }
}
// OK: no conversion required.
var tag2 = new GenericTag<Int64>(Int64.MaxValue);
// OK: implicit conversion takes place.
var tag1 = new GenericTag<Int64>(Int32.MaxValue);
// Compile error: cannot convert from long to int.
var tag4 = new GenericTag<Int32>(Int64.MaxValue);
// Compile error: cannot convert from string to long.
var tag3 = new GenericTag<Int64>("foo");
如果您知道需要Int64,為什么不使用Convert.ToInt64?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.