简体   繁体   English

C# 预处理器警告如果会导致编译错误

[英]C# preprocessor warning if will cause compile error

I'm using unity I want to wrap my class in a #if UNITY_EDITOR.我正在使用统一我想将我的 class 包装在 #if UNITY_EDITOR 中。 I can still access that class from other scripts without the if statement causing errors and no warning to other programmers until build compilation.我仍然可以从其他脚本访问该 class 而不会导致错误的 if 语句并且在构建编译之前不会向其他程序员发出警告。

Example:例子:

#if UNITY_EDITOR
using UnityEditor
public class ObservableEditor : Editor
{
    //Code here
}
#endif
public class AnotherClass
{
   public AnotherClass()
   {
        //Call ObservableEditor Observables
        //causes error if not in unity editor programmer is unaware until build
   }
}

Is there a good way to throw a warning to other programmers so they know to use the preprocessor?有没有一种好方法可以向其他程序员发出警告,以便他们知道使用预处理器?

As far as I know, there is no easy way to issue a warning for when this happens, but C# does have a very neat attribute that may a accomplish what you want.据我所知,没有简单的方法可以在发生这种情况时发出警告,但是 C# 确实有一个非常简洁的属性,可以实现您想要的。 The Conditional attribute makes so the class/method is only compiled when the provided pre-processor is defined, but if the class/method is called somewhere else it won't throw any errors, even it the pre-processor is not defined Conditional属性使得类/方法仅在定义了提供的预处理器时才被编译,但是如果在其他地方调用类/方法,它不会抛出任何错误,即使没有定义预处理器

I think that if you use it like this it will work:我认为,如果您这样使用它,它将起作用:

 using UnityEditor
    
 [System.Diagnostics.Conditional("UNITY_EDITOR")]
 public class ObservableEditor : Editor
 {
     //Code here
 }

The only problem is that the programmer will still be unaware that the class/method is only present in the editor, but there are other ways to communicate that, like putting the class in an editor namespace and in an editor assembly definition so that unity will give an error even while in the editor唯一的问题是程序员仍然不知道类/方法只存在于编辑器中,但还有其他方式可以传达这一点,例如将 class 放在编辑器命名空间和编辑器程序集定义中,以便统一即使在编辑器中也会出错

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM