繁体   English   中英

C#ChangeType和ToString?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM