zoukankan      html  css  js  c++  java
  • 属性,特性,反射等。

    大全

    加载程序集

    Assembly theAssembly = Assembly.Load("VectorClass");//这里VectorClass是程序引用的一个dll
    Assembly.LoadFrom(@"D:ClassLibrary1.dll");//LoadFrom需dll全路径

     反射得到类,创建实例

    // 用命名空间+类名获取类型
    typeA = ass.GetType("ClassLibrary1.ReflectTestClass");
                    
    // 获得方法名称
    MethodInfo method = typeA.GetMethod("writeString");
    
    // 创建实例
     obj = ass.CreateInstance("ClassLibrary1.ReflectTestClass");
    //调用方法

    string result = (String)method.Invoke(obj,new string[] {"Tom"});

     一般用Activator.CreateInstance创建对象

    bool IsAssignableFrom(Type t):是否可以从t赋值,判断当前的类型变量是不是可以接受t类型变量的赋值。
    bool IsInstanceOfType(object o):判断对象o是否是当前类的实例,当前类可以是o的类、父类、接口
    bool IsSubclassOf(Type t):判断当前类是否是t的子类

    获取程序集中的某个属性

    Attribute supportsAttribute =Attribute.GetCustomAttribute(theAssembly, typeof (SupportsWhatsNewAttribute));

    获取该程序集所有类型

    Type[] types = theAssembly.GetTypes();
    foreach (Type type in types)
    {
    // 获取类型的结构信息
     ConstructorInfo[] myconstructors = type.GetConstructors();
    
    // 获取类型的字段信息
     FieldInfo[] myfields = type.GetFields();
    
    // 获取方法信息
    MethodInfo[] myMethodInfo = type.GetMethods();
    
    // 获取属性信息
    PropertyInfo[] myproperties = type.GetProperties();
    
    //获取特性信息
    Attribute[] attribs = Attribute.GetCustomAttributes(type);
    }

    从任意地方获取某一个类中某一个属性的字符串名称

    比如

        public class SomeThing
        {
            public string JustTest
            { get; set; }
    
        }

    想要通过new SomeThing.JustTest返回"JustTest"

            public static string GetMemberName(LambdaExpression lambda)
            {
                var member = lambda.Body as MemberExpression;
                if (member == null) throw new NotSupportedException(
                      "The final part of the lambda is not a member-expression");
                return member.Member.Name;
            }

    使用方式

                Expression<Func<object>> expr = () => new SomeThing().JustTest;
                Console.WriteLine("This is "+Utils.GetMemberName(expr));

    结果:This is JustTest

    在getter或者setter中获取当前属性的字符串名称

        public class SomeThing
        {
            public string JustTest
            { get 
                {
                    Console.WriteLine("Current property is " + ReflectionUtils.GetCallerName());
                    return "FOO";
                } 
                set { } 
            }
    
        }

    执行

    Console.WriteLine(new SomeThing().JustTest);

    返回

    Current property is JustTest
    FOO

    其中

            public static string GetCallerName([CallerMemberName] string name = null)
            {
                return name;
            }

     方式二,改成

    Console.WriteLine("Current property is " + MethodBase.GetCurrentMethod().Name);
                    return "FOO";

    返回

    Current property is get_JustTest
    FOO

    搜索类的特性,打印特性中的信息

        internal class JustAnAttribute : Attribute
        {
            private readonly string para;
            public JustAnAttribute(string para)
            {
                this.para = para;
            }
            public string OnePara { get { return para; } }
        }

    特性的使用

        [JustAn("Hello")]
        public class SomeThing
        {
    
        }

    代码

                Type t = typeof(SomeThing);
                Attribute[] attri = Attribute.GetCustomAttributes(t,typeof(JustAnAttribute));
                foreach(Attribute _a in attri)
                {
                    JustAnAttribute a = _a as JustAnAttribute;
                    if(a!=null)
                    {
                        Console.WriteLine(a.OnePara);
                    }
                }

    搜索类下面方法,获取其特性

    MethodInfo[] methods = type.GetMethods();
                foreach (MethodInfo nextMethod in methods)
                {
                    object[] attribs2 =
                        nextMethod.GetCustomAttributes(
                            typeof (LastModifiedAttribute), false);

     获取类下面某个属性的特性信息

    typeof(Book)
      .GetProperty("Name")
      .GetCustomAttributes(false) 

    或者

    public class Book
    {
        [Author("AuthorName")]
        public string Name
        {
            get; private set; 
        }
    }
    
    
    
    PropertyInfo[] props = typeof(Book).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                AuthorAttribute authAttr = attr as AuthorAttribute;
                if (authAttr != null)
                {
                    string propName = prop.Name;
                    string auth = authAttr.Name;
    
                    
                }
            }
        }

     通过包名搜索接口的实现类,并且实例化对象

            public static Type GetDerivativeTypesByPackageName(Type interfaceName)
            {
                return Assembly.GetExecutingAssembly().GetTypes()
                    .Where(t => t.GetInterface(interfaceName.Name) != null && t.Namespace.EndsWith(GlobalSwitch.GS))
                    .FirstOrDefault();
            }
    
            public static T Autowire<T>()
            {
                Type t=GetDerivativeTypesByPackageName(typeof(T));
                if (t == null)
                    return default(T);
                return (T)Activator.CreateInstance(t);
            }
  • 相关阅读:
    Postman使用教程
    CAD和ArcGIS转换 矢量配准
    SAP CRM Advanced search和Simple search里Max hit表现行为的差异
    SAP CRM Product simple search的启用步骤
    如何快速定位SAP CRM订单应用(Order Application)错误消息抛出的准确位置
    如何动态修改SAP CRM WebClient UI表格栏的宽度
    如何在SAP CRM WebClient UI里创建web service并使用ABAP消费
    如何处理SAP CRM Web Service错误
    如何使用SAP CRM WebClient UI实现一个类似新浪微博的字数统计器
    如何开启SAP CRM基于WORD模板创建附件的功能
  • 原文地址:https://www.cnblogs.com/noigel/p/14376529.html
Copyright © 2011-2022 走看看