Unity的[Obsolete]属性

参考:https://www.tutorialspoint.com/What-are-obsolete-attributes-in-Chash
参考:https://docs.microsoft.com/en-us/dotnet/api/system.obsoleteattribute?view=net-6.0
参考:https://stackoverflow.com/questions/31804260/do-unity-functions-that-are-obsolete-still-work

C#自身就有一个ObsoleteAttribute类,其实Unity用的就是它:

namespace System
{
    
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
    public sealed class ObsoleteAttribute : Attribute
    {
    
    
        public ObsoleteAttribute();
        public ObsoleteAttribute(string message);
        public ObsoleteAttribute(string message, bool error);

        public bool IsError {
    
     get; }
        public string Message {
    
     get; }
    }
}

只要把这个Attribute加到Method上面,编译器会去检测,当Method被调用时,就发出Warning或Error。可以看到ObsoleteAttribute的构造函数最多接受俩参数,第二个参数为true,则编译器会编译失败,生成Error,否则生成Warning,具体的信息由第一个参数message表示。

用法很简单,用于过时的Method上,Unity官方在更新它的C#代码时,经常使用这个Attribute,写法如下:

using System;

public class Demo {
    
    

	// 保留原本的代码, 添加Obsolete属性
   [Obsolete("Old Method shouldn't be used! Use New Method instead", true)]
   static void OldMethod() 
   {
    
    
      Console.WriteLine("This is the old method!");
   }

   static void NewMethod() 
   {
    
    
      Console.WriteLine("This is the new method!");
   }

   public static void Main() 
   {
    
    
      OldMethod();
   }
}

也可以啥都不写[Obsolete]:

public class TestAnimation : MonoBehaviour
{
    
    
	// 输出Assets\TestAnimation.cs(49,9): warning CS0618: 'TestAnimation.FFF()' is obsolete: 'FF'
    [Obsolete("FF")]
    public void FFF()
    {
    
    
    }

    // 输出Assets\TestAnimation.cs(56,9): warning CS0612: 'TestAnimation.SSS()' is obsolete    
	[Obsolete]// 其实这玩意儿对于代码执行, 没有任何影响
    public void SSS()
    {
    
    
    }

	void Start()
    {
    
    
        FFF();
        SSS();// 必须得用上才会有编译提示
	}
}

最后顺便说一句,这一部分的内容是写到C#编译器里的(ObsoleteAttribute is effectively hard-coded into the C# compiler ),所以要想实现自己版本的CustomObsoleteAttribute,几乎是不太可能的。

猜你喜欢

转载自blog.csdn.net/alexhu2010q/article/details/125655040