天天看点

dynamic与反射补充

这里做一个补充知识

之前在讲dynamic、反射和特性的时候遗漏了一个小问题

如果有不知道[Conditional(“XXX”)]用法的可以看我之前的特性文章这里就不说了

反射出来被[Conditional(“XXX”)]修饰的方法条件能否起作用

这个是我们定义好的类和特性

[AttributeUsage(AttributeTargets.All,AllowMultiple = true,Inherited = true)]
public class InfoAttribute : Attribute
{
    public string Name { get; set; }

    public int Age { get; set; }

    public InfoAttribute(string name,int age)
    {
        Name = name;
        Age = age;
    }
}

[InfoAttribute("英雄类名",255), InfoAttribute("英雄装备", 1024)]
public class HeroInfo
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="name"></param>
    /// <param name="level"></param>
    /// <param name="price"></param>
    public HeroInfo(string name,int level,decimal price)
    {
        Name = name;
        Level = level;
        Price = price;
    }

    [InfoAttribute("Qin", 24), InfoAttribute("Liu", 23)]
    public string Name { get; set; }

    public int Level { get; set; }

    [InfoAttribute("Hui", 10), InfoAttribute("Bui", 10)]
    public decimal Price { get; set; }


    [Obsolete("此方法过时,请使用Test代替",false)]
    [System.Diagnostics.Conditional("Bef")]
    public void BefTest(int i)
    {
        Debug.LogError("===========>BefTest===>" + i);
    }

    [System.Diagnostics.Conditional("Now")]
    public void NowTest(int i)
    {
        Debug.LogError("===========>NowTest===>" + i);
    }
}
           

对反射出来的方法进行测试

#define Now
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class PropertyTest : MonoBehaviour {

	// Use this for initialization
	void Start () {
        HeroInfo heroInfo = new HeroInfo("李白",18,14353);

        heroInfo.BefTest(1);
        heroInfo.NowTest(2);

        var beftestMethod = heroInfo.GetType().GetMethod("BefTest");
        beftestMethod.Invoke(heroInfo,new object[] { 3 });

        var nowtestMethod = heroInfo.GetType().GetMethod("NowTest");
        nowtestMethod.Invoke(heroInfo, new object[] { 4 });

    }

}
           

结果如下图:

dynamic与反射补充

发现特性条件修饰已经不起任何作用

简化反射dynamic出来被[Conditional(“XXX”)]修饰的方法条件能否起作用?

对简单反射出来的方法进行测试

#define Now
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class PropertyTest : MonoBehaviour {

	// Use this for initialization
	void Start () {
        HeroInfo heroInfo = new HeroInfo("李白",18,14353);

        heroInfo.BefTest(1);
        heroInfo.NowTest(2);

        dynamic dy = heroInfo;
        dy.BefTest(5);
        dy.NowTest(6);

    }

}
           
dynamic与反射补充

发现特性条件修饰已经不起任何作用

总结

也就是说当我们使用反射和dynamic时要注意,我们当初添加的特性条件是不起作用的,个人猜想是因为反射出来的方法与类调用的方法处理方式不同,因为特性是一个特殊实例化情况的类,所以在反射调用方法时,它的特性没有被实例化,也就是没有起到作用,所以这里才不会起作用。

dynamic不能直接做反射获取添加的元数据,只能对dynamic赋值时的类进行反射;

继续阅读