c# - 如何扩展类型类

标签 c# .net extension-methods

这是我的代码:

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新方法扩展Type类

最佳答案

您不能有静态扩展方法。您的扩展方法适用于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")


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

关于c# - 如何扩展类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18531218/

相关文章:

c# - 如何扩展同名方法并被调用?

c# - 序列化期间奇怪的内存不足异常

c# - ASP 网站似乎没有在 Web.Config 中使用 machineKey 进行 FormsAuthentication.Decrypt

c# - 在 C# 应用程序中使用 MsgPack 自定义序列化程序

c# - 对象的通用列表包含短返回 false

c# - 未优化的 IEnumerable<>.Last with predicate

C# - 对 IEnumerable<T> 的操作

c# - WPF,学习滚动条样式

c# - 使用模式 range/start//end/搜索 String 或 StringBuilder

c# - ftpwebrequest.getresponse 抛出 550 拒绝访问