Determine if a type is static

前端 未结 5 763
梦谈多话
梦谈多话 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
    }
    

提交回复
热议问题