2013-08-30 185 views
1

这是我的代码:如何扩展类型类

bool ch=Type.IsBuiltIn("System.Int32"); // not working-> syntax error 


public static class MyExtentions 
    {    
     public static bool IsBuiltIn(this Type t, string _type) 
     { 
      return (Type.GetType(_type) == null) ? false : true; 
     } 
    } 

请我想IsBuiltIn新方法

+0

这里你不需要扩展方法 –

+0

把'typeof(int).IsBuiltIn'写到你的编辑器中。你看到了什么? – I4V

+0

您传递给IsBuiltIn()方法的字符串应该是该类型的程序集限定名称。我的意思是你应该通过System.Int32 insted只是int – Dimitri

回答

6

您不能有静态扩展方法。您的扩展方法适用于Type类的一个实例,所以叫它你必须做这样的事情:

typeof(Type).IsBuiltIn("System.Int32") 

这种情况的解决方法是,只要把你的扩展方法的实用类,例如像下面,并把它像一个正常的静态函数:

public static class TypeExt 
{    
    public static bool IsBuiltIn(string _type) 
    { 
     return Type.GetType(_type) == null; 
    } 
} 

// To call it: 
TypeExt.IsBuiltIn("System.Int32") 

顺便说一句,我不认为这会告诉你的类型是否“内置”;它只会告诉你是否已将具有给定名称的类型加载到进程中。

0

扩展类型类不能扩展的Type类。您需要该类的一个实例来创建扩展方法。

编辑: 请参阅herehere

+0

为什么?你为什么不能这样做? –

+0

你为什么低调?看我的编辑。 – Loetn

+0

@SriramSakthivel不,你需要一个类类型的实例。你不能扩展类的类型。 – Maarten

3

扩展方法旨在描述实例的新API,而不是类型。在你的情况下,该API将是这样的:

Type someType = typeof(string); // for example 
bool isBuiltIn = someType.IsBuiltIn("Some.Other.Type"); 

其中......显然不是你想要的; type这里什么也不加,并且与IsBuiltIn没有关系。没有编译器技巧用于将新的静态方法添加到现有类型,基本上 - 因此您将无法使用Type.IsBuiltIn("Some.Other.Type")