开发者

.Net generic contraint on struct types

I am trying to create a generic class whose implementation depends on the type being an Int32, Int64, double, float, or decimal.

class Calculator<开发者_如何学C;T> where T: int, double, float, decimal

This is not right but I'm having troubles with the syntax


I am trying to create a generic class whose implementation depends on the type being an Int32, Int64, double, float, or decimal.

Then it is not generic. A generic type is one that works the same way for all possible type arguments, like a generic queue or a generic dictionary.

"Calculator" classes are the most common scenario given for a feature like that; we get this feature request all the time. We are hypothetically considering it for a hypothetical future version of C# that has not been announced and does not exist. Doing the feature right would require considerable support from a hypothetical future version of the CLR that also has not been announced and does not exist. The scenario is not a particularly high priority as these things go, so please do not be disappointed if it does not come to pass.

There are a number of ways such a feature could be surfaced. For example, we could say that you can put static methods in interfaces. Math operators are static methods, and so then you could constrain a type parameter to be a type that implements static interface IAddable, or some such thing.

Remember any musings Eric makes about the future of unannounced products that do not exist and might never exist is for your entertainment only.


You can't specify a constraint on a type parameter such that it has to be one of a specified set of types, no. See MSDN for a list of valid constraints.

For those particular types you could specify:

where T : struct, IComparable, IFormattable, IConvertible,
          IComparable<T>, IEquatable<T>

That's likely to restrict the set fairly well, although it would also allow other primitive types such as byte and ulong.


You can't do that. You can only do it to an interface, class, struct, or empty constructor (new()), or a base class.

See: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

The closest would be struct, IConvertable.

One technique I have seen is to use the static constructor and throw asserts or exceptions, but this is not compile time checking, only runtime.

class Calculator<T>  
   where T : struct
{
   static Calculator()
   {
     Debug.Assert(typeof(T) == typeof(int), "FAIL"); //TODO: extend to other types
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜