1

this is my code:

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;
        }
    }

Please I want Extend Type Class by IsBuiltIn new method

4

3 回答 3

6

You can't have static extension methods. Your extension method works on an instance of the Type class, so to call it you'd have to do something like this:

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

The workaround for this is to just put your extension method in a utility class, e.g. like the following, and call it like a normal static function:

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

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

By the way, I don't think this will tell you whether the type is "built-in"; it will merely tell you whether a type with the given name has been loaded into the process.

于 2013-08-30T11:19:17.083 回答
3

Extension methods are intended to describe new APIs on instances, not types. In your case, that API would be something like:

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

which... clearly isn't what you wanted; the type here adds nothing and is not related to the IsBuiltIn. There is no compiler trick for adding new static methods to existing types, basically - so you will not be able to use Type.IsBuiltIn("Some.Other.Type").

于 2013-08-30T11:20:45.507 回答
0

You can't extend the Type class. You need an instance of the class to create an extension method.

Edit: See here and here.

于 2013-08-30T11:03:39.943 回答