泛型类型检查 [英] Generic type checking

查看:205
本文介绍了泛型类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法强制执行/限制传递给原语的类型? (BOOL,INT,字符串,等等。)

现在,我知道你可以通过的其中的子句中的泛型类型参数限制为一类或接口实现。但是,这并不适合原语(据我所知)该法案,因为他们并不都具有一个共同点(除了的对象的前有人说:P)。

Now, I know you can limit the generic type parameter to a type or interface implementation via the where clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from object before someone says! :P).

所以,我目前的想法是只是砂砾我的牙齿和做大的开关的语句,并抛出的的ArgumentException 的失败..

So, my current thoughts are to just grit my teeth and do a big switch statement and throw an ArgumentException on failure..

修改1:

只是为了澄清

中的代码定义应该是这样的:

The code definition should be like:

public class MyClass<GenericType> ....

和实例:

MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)






< STRONG>编辑2

@乔恩Limjap - 好一点,有什么东西我已在考虑。我敢肯定有,可以是一个通用的方法用于确定如果类型是一个值或引用类型..

@Jon Limjap - Good point, and something I was already considering.. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type..

这可能是有用的瞬间去除大量的对象的我不想处理(但那么你需要担心使用如结构的大小的)..有趣的问题没有? :)

This could be useful in instantly removing a lot of the objects I dont want to deal with (but then you need to worry about the structs that are used such as Size ).. Interesting problem no? :)

下面是:

where T : struct

从的MSDN

我很好奇..难道这中完成。使用扩展方法NET 3.x的?创建一个接口,并实现在扩展方法的接口(这可能会比一个有点胖开关清洁剂)。另外,如果你再以后需要扩展到任何轻量级的自定义类型,他们也可以实现相同的接口,有需要的基本代码进行任何更改。

I'm curious.. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.

你们有什么觉得呢?

噩耗是我在Framework 2 WORKING !! :D

Sad news is I am working in Framework 2!! :D

修改3

这是如此简单,从乔恩Limjaps指针继..所以简单的我几乎要!哭,但因为代码就像一个魅力这是伟大的。

This was so simple following on from Jon Limjaps Pointer.. So simple I almost want to cry, but it's great because the code works like a charm!

因此,这里是我做了什么(你会笑!):

So here is what I did (you'll laugh!):

bool TypeValid()
{
    // Get the TypeCode from the Primitive Type
    TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));

    // All of the TypeCode Enumeration refer Primitive Types
    // with the exception of Object and Empty (Null).
    // Since I am willing to allow Null Types (at this time)
    // all we need to check for is Object!
    switch (code)
    {
        case TypeCode.Object:
            return false;
        default:
            return true;
    }
}



这时,一个小实用程序方法检查类型并引发一个例外,

Then a little utility method to check the type and throw an exception,

private void EnforcePrimitiveType()
{
    if (!TypeValid())
        throw new InvalidOperationException(
            "Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name + 
            "' - this Class is Designed to Work with Primitive Data Types Only.");
}



所有这一切,然后需要做的是调用的 EnforcePrimitiveType() 的在类的构造函数。任务完成! : - )

All that then needs to be done is to call EnforcePrimitiveType() in the classes constructors. Job done! :-)

只有一个缺点,它只能抛出在运行时(显然)而不是设计时例外。但是这没什么大不了的,并可以与被拾起如的FxCop 公用事业(我们不要在工作中使用)。

The only one downside, it only throws an exception at runtime (obviously) rather than design time.. But that's no big deal and could be picked up with utilities like FxCop (which we don't use at work).

特别感谢乔恩Limjap在这一个!

Special thanks to Jon Limjap on this one!

推荐答案

基元出现在的 类型码 枚举:

Primitives appear to be specified in the TypeCode enumeration:

也许还有就是要找到出路,如果一个对象包含的TypeCode枚举,而无需将其转换为特定的对象或拨打的GetType() typeof运算()

Perhaps there is a way to find out if an object contains the TypeCode enum without having to cast it to an specific object or call GetType() or typeof()?

更新这是对我的鼻子底下。代码示例有表明这一点:

Update It was right under my nose. The code sample there shows this:

static void WriteObjectInfo(object testObject)
{
    TypeCode    typeCode = Type.GetTypeCode( testObject.GetType() );

    switch( typeCode )
    {
        case TypeCode.Boolean:
            Console.WriteLine("Boolean: {0}", testObject);
            break;

        case TypeCode.Double:
            Console.WriteLine("Double: {0}", testObject);
            break;

        default:
            Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
            break;
        }
    }
}



这仍然是一个丑陋的开关。但它是一个良好的开端!

It's still an ugly switch. But it's a good place to start!

这篇关于泛型类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆