![](/img/trans.png)
[英]In C# Convert.ChangeType(jobj[p.Name].ToString(), p.ParameterType))
[英]C# ChangeType and ToString?
我想將int轉換為特定類型,然后返回一個字符串,其格式取決於我將其轉換為的類型。
我有一個返回Type對象的屬性,另一個我想返回一個字符串,其格式取決於Type。
為什么編譯器不喜歡下面HexString中的代碼?
還有另一種同樣簡短的方法嗎?
public class TestClass
{
private int value;
public bool signed;
public int nBytes;
public int Value { get {return value;} set {this.value = value;}}
public Type Type {
get {
switch (this.nBytes) {
case 1:
return (this.signed ? typeof(SByte) : typeof(Byte));
case 2:
return (this.signed ? typeof(Int16) : typeof(UInt16));
default:
return null;
}
}
}
public String HexString {
get {
//?? compiler error: "no overload for method 'ToString' takes '1' arguments
return (Convert.ChangeType(this.Value, this.Type)).ToString("X" + this.nBytes);
}
}
}
嘗試通過String.Format
而不是使用Object.ToString()
格式化字符串:
return String.Format("{0:x" + this.nBytes.ToString() + "}",
(Convert.ChangeType(this.Value, this.Type)));
任何實現格式化表格ToString()
方法的類型都不會覆蓋System.Object.ToString()
,因此,您不能在帶有參數的Object
上調用該方法。
ChangeType返回一個System.Object。 不幸的是,只有數字類型提供了具有格式(字符串參數)的ToString重載。 System.Object.ToString()不接受任何參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.