简体   繁体   中英

How to Extend the Type Class

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

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, eg 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.

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") .

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

Edit: See here and here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM