我希望将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);
}
}
}发布于 2009-08-05 19:09:39
尝试通过String.Format而不是使用Object.ToString()设置字符串的格式
return String.Format("{0:x" + this.nBytes.ToString() + "}",
(Convert.ChangeType(this.Value, this.Type)));任何实现可格式化ToString()方法的类型都不会重写System.Object.ToString(),因此不能使用参数在Object上调用该方法。
发布于 2009-08-05 19:10:14
ChangeType返回一个System.Object。不幸的是,只有数值类型提供了带有格式(字符串参数)的ToString重载。System.Object.ToString()不带任何参数。
https://stackoverflow.com/questions/1235138
复制相似问题