Determine if a type is static

前端 未结 5 743
梦谈多话
梦谈多话 2020-11-29 08:49

Let\'s say I have a Type called type.

I want to determine if I can do this with my type (without actually doing this to each type):

相关标签:
5条回答
  • 2020-11-29 09:27

    you can search for public contructors like this,

    Type t = typeof(Environment);
    var c = t.GetConstructors(BindingFlags.Public);
    if (!t.IsAbstract && c.Length > 0)
    {
         //You can create instance
    }
    

    Or if you only interested in parameterless constructor you can use

    Type t = typeof(Environment);
    var c = t.GetConstructor(Type.EmptyTypes);
    if (c != null && c.IsPublic && !t.IsAbstract )
    {
         //You can create instance
    }
    
    0 讨论(0)
  • 2020-11-29 09:29

    static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case).

    However, abstract classes are not the only types you can't instantiate directly. You should check for things like interfaces (without the CoClass attribute) and types that don't have a constructor accessible by the calling code.

    0 讨论(0)
  • 2020-11-29 09:29

    This is a way to get all public contstuctors of all types in an assembly.

        var assembly = AppDomain.CurrentDomain.GetAssemblies()[0]; // first assembly for demo purposes
    var types = assembly.GetTypes();
    foreach (var type in types)
    {
        var constructors = type.GetConstructors();
    }
    
    0 讨论(0)
  • 2020-11-29 09:39
    type.IsAbstract && type.IsSealed
    

    This would be a sufficient check for C# since an abstract class cannot be sealed or static in C#. However, you'll need to be careful when dealing with CLR types from other languages.

    0 讨论(0)
  • 2020-11-29 09:41
    Type t = typeof(System.GC);
    Console.WriteLine(t.Attributes);
    TypeAttributes attribForStaticClass = TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class |
    TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit;
    Console.WriteLine((t.Attributes == attribForStaticClass));
    

    I guess, this should work.

    0 讨论(0)
提交回复
热议问题