我想將任何整數型別轉換為十六進制字串表示并回傳。我想出了類似下面的東西,但它顯然有錯誤。在 C# 中這樣做有什么建議嗎?提前致謝。
public class HexCnv<T>
{
public static T ToIntType(string sInput)
{
return T.Parse(sInput.TrimStart('0', 'x'));
}
public static string ToStringType(T nInput)
{
return "0x" nInput.ToString("X2");
}
}
uj5u.com熱心網友回復:
沒有將泛型引數限制為整數型別的泛型約束,并且您不能Parse在泛型型別上呼叫靜態方法(如 )。您可以在任何地方使用隱式轉換和使用long(或可能ulong),或者為每個整數型別提供多載 - 盡管您只需要該ToIntType方法,因為它會為您提供與轉換為 a相同ToStringType的結果a 。bytebytelong
uj5u.com熱心網友回復:
這個作業怎么樣?(未測驗)
public class HexCnv<T>
{
public static readonly TypeCode typeCode = Type.GetTypeCode(typeof(T));
public static T ToIntType(string sInput)
{
switch (typeCode)
{
case TypeCode.Int32:
return Int32.Parse(sInput.TrimStart('0', 'x'));
case TypeCode.Int64:
return Int64.Parse(sInput.TrimStart('0', 'x'));
...
...
...
}
throw new ArgumentException(nameof(sInput));
}
public static string ToStringType(T nInput)
{
return "0x" nInput.ToString("X2");
}
}
uj5u.com熱心網友回復:
我找到了包含您所有想法的解決方案,非常感謝。我已經測驗了以下代碼,它按照我想要的方式作業,并且我用一般的感覺來制作它;我可以測驗其他方法來檢查代碼效率,但它適用于我,我希望這個想法適用于其他任何人:
public class HexCnv<T>
{
private MethodInfo _mParse;
private MethodInfo _mToString;
private T _value;
private bool _isPrimitive;
public HexCnv(T v)
{
Type t = typeof(T);
_isPrimitive = t.IsPrimitive;
_value = v;
_mParse = t.GetMethod("Parse", new Type[] { typeof(string), typeof(NumberStyles) });
_mToString = t.GetMethod("ToString", new Type[] { typeof(string) });
}
public HexCnv(string v)
{
Type t = typeof(T);
_isPrimitive = t.IsPrimitive;
_mParse = t.GetMethod("Parse", new Type[] { typeof(string), typeof(NumberStyles) });
_mToString = t.GetMethod("ToString", new Type[] { typeof(string) });
FromString(v);
}
private void FromString(string s)
{
if (_isPrimitive && _mParse != null)
_value = (T)_mParse.Invoke(null, new object[] { s.TrimStart('0', 'x'), NumberStyles.HexNumber });
}
public new string ToString()
{
string sOut = string.Empty;
if (_isPrimitive) sOut = "0x" _mToString.Invoke(_value, new object[] { "x2" }).ToString();
return sOut;
}
public static implicit operator T(HexCnv<T> v) { return v._value; }
public static implicit operator HexCnv<T>(T v) { return new HexCnv<T>(v); }
public static implicit operator HexCnv<T>(string v) { return new HexCnv<T>(v); }
}
如您所見,我更改了靜態方法,并使其與簡單分配一起作業,請參見下一個片段:
HexCnv<short> mm = "0x1f55";
Console.WriteLine("MM = {0}", (int) mm);
Console.WriteLine("MM-HEX = {0}", mm.ToString());
//This produce the following result
// MM = 8021
// MM-HEX = 0x1f55
HexCnv<short> mm = "0x8f55"; //IDE show no errors on this, but
HexCnv<short> mm = 0x8f55; //It'll give an error on this expression,
//cuz the number is higher than "short"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482052.html
