页首Html代码

属性,特性,反射等。

大全

加载程序集

反射当前项目中的类

Assembly ass=Assembly.GetExecutingAssembly();

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);
}

 Model和XElement互相转换

这里Model的属性都是普通类型

        public static XElement Model2Element(object obj)
        {
            Type type = obj.GetType();
            XElement element = new XElement(type.Name);
            type.GetProperties().ToList().ForEach(prop =>
                {
                    string propName = prop.Name;
                    string y = prop.PropertyType.Name;
                    XElement tmp = new XElement(propName);
                    tmp.Value = Convert.ToString(prop.GetValue(obj, null));
                    element.Add(tmp);
                }
            );
            return element;
        }

        public static T Element2Model<T>(XElement element) where T:new ()
        {
            string Name = element.Name.ToString();
            T model = new T();
            if (model.GetType().Name != Name)
                return default(T);
            var props=model.GetType().GetProperties();
            element.Elements().ToList().ForEach(e =>
            {
               PropertyInfo theOne =props.Where(x => x.Name == e.Name).FirstOrDefault();
                if(theOne != null && !theOne.PropertyType.IsGenericType)
                {
                    var res=Convert.ChangeType(e.Value, theOne.PropertyType);
                    theOne.SetValue(model, res,null);
                }
            });
            return model;
        }

较复杂的参考https://www.cnblogs.com/feiyuhuo/p/5493354.html

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

比如

    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; } }
    }

定义特性类的时候,可以在上面加上特性

[AttributeUsage(
   validon,
   AllowMultiple=allowmultiple,
   Inherited=inherited
)]
validon默认使用所有,类,方法,属性,。。
AllowMultiple表示可以和其他特性合用
Inherited表示可以被子类继承


[Conditional("DEBUG")]表示只有在debug的时候才运行

特性的使用

 

    [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);
        }

 

posted @ 2021-02-05 10:57  noigel  阅读(74)  评论(0编辑  收藏  举报
js脚本