我使用了hack-solution:接口。 見內置值類型和字符串類型已實現的接口:
struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool>
struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
struct UInt64 : IComparable, IFormattable, IConvertible, IComparable<ulong>, IEquatable<ulong>
struct Single : IComparable, IFormattable, IConvertible, IComparable<float>, IEquatable<float>
struct Byte : IComparable, IFormattable, IConvertible, IComparable<byte>, IEquatable<byte>
struct Char : IComparable, IConvertible, IComparable<char>, IEquatable<char>
struct Decimal : IFormattable, IComparable, IConvertible, IComparable<decimal>, IEquatable<decimal>
可以使用IComparable,IConvertible,IEquatable<T>
進行約束。 像這樣:
public static void SetValue<T>(T value) where T : IComparable, IConvertible, IEquatable<T>
{
//TODO:
}
或者你可以使用類型代碼來檢查數據的時間沒有限制。
public static void SetValue<T>(T value)
{
switch (Type.GetTypeCode(typeof(T)))
{
#region These types are not what u want, comment them to throw ArgumentOutOfRangeException
case TypeCode.Empty:
break;
case TypeCode.Object:
break;
case TypeCode.DBNull:
#endregion
break;
case TypeCode.Boolean:
break;
case TypeCode.Char:
break;
case TypeCode.SByte:
break;
case TypeCode.Byte:
break;
case TypeCode.Int16:
break;
case TypeCode.UInt16:
break;
case TypeCode.Int32:
break;
case TypeCode.UInt32:
break;
case TypeCode.Int64:
break;
case TypeCode.UInt64:
break;
case TypeCode.Single:
break;
case TypeCode.Double:
break;
case TypeCode.Decimal:
break;
case TypeCode.DateTime:
break;
case TypeCode.String:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
請記住,不要使用對象類型,但對參數類型使用泛型類型。否則,當值爲空時,您可能會在代碼行Type.GetTypeCode(value.GetType())
處獲得NULL EXCEPTION。
對於您的實現,什麼使值類型和字符串在別人不可用的地方接受? – 2012-01-05 15:58:34