【发布时间】:2018-03-18 02:22:01
【问题描述】:
我已经知道在方法上使用条件属性有一段时间了,但我刚刚发现它也可以在属性类上使用,所以我写了一些代码来测试它,但它没有达到预期的效果。
此 MSDN 页面显示如何在页面底部的属性类上使用条件属性:https://msdn.microsoft.com/en-us/library/4xssyw96%28v=vs.90%29.aspx。
顺便说一句,我正在使用 Unity 引擎。我认为这无关紧要,但我可能猜到了。
这是我写的测试代码:
using System.Reflection;
using UnityEngine;
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public class TestAttribute : System.Attribute
{
public string text;
public TestAttribute(string text)
{
this.text = text;
}
}
public class NewBehaviourScript : MonoBehaviour
{
[Test("This shouldn't exist on android")]
public void Awake()
{
#if UNITY_EDITOR
Debug.Log("This only gets logged in the Unity Editor, not in an Android build");
#endif
Debug.Log("Begin Attribute Test");
{
object[] attributes = typeof(NewBehaviourScript).GetMethod("Awake").GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
Debug.Log(attributes[i]);// This logs TestAttribute both in the editor and on android.
}
TestAttribute att = attributes[0] as TestAttribute;
Debug.Log(att.text);// This logs "This shouldn't exist on android" both in the editor and on android.
}
Debug.Log("End Attribute Test");
Debug.Log("");
Debug.Log("Begin Method Test");
{
Method();// This only gets called in the Unity Editor, as expected from the conditional attribute.
MethodInfo methodInfo = typeof(NewBehaviourScript).GetMethod("Method");
Debug.Log(methodInfo);// this logs "void Method()" both in the editor and on android.
}
Debug.Log("End Method Test");
}
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public void Method()
{
Debug.Log("This shouldn't exist on android either");
}
}
如果条件属性没有阻止 GetCustomAttributes() 获取测试属性,它实际上做了什么?
【问题讨论】: