我如何显式键入静态变量,而不是隐式键入 (var)?

Instead of implicitly typing (var), how do I explicitly type static variables?

目前我隐式输入了eventOperation

var eventOperation = EventOperations.Cancel;

但我明确地键入了 eventOperation,这样我就不必在 if 语句之前分配任意值。另外,我无法在 if 语句中初始化变量或具有未初始化的隐式类型变量。

这是我对静态的定义 class:

public static class EventOperations
{
    ...
    public static OperationAuthorizationRequirement Cancel =
      new OperationAuthorizationRequirement { Name = Constants.CancelOperationName };
}

public class Constants
{
    ...
    public static readonly string CancelOperationName = "Cancel";
    ...
}

EventOperations.Cancel显然是OperationAuthorizationRequirement类型。所以只需将您的变量声明为

OperationAuthorizationRequirement eventOperation = EventOperations.Cancel;

另一种方法是:

var eventOperation = null as EventOperations;

这样您仍然可以使用 var(隐式)声明您的变量,但在右侧指定数据类型,以便编译器能够识别出来。

更新

您原来的 post 意味着 static 变量声明。我不确定你在这里是否正确使用了这个术语,但如果你这样做了,情况就会稍微改变...

由于 C# 不支持静态局部变量,您需要在模块级别将变量声明为 static,即不在方法内,而是直接在 class.

public class SomeClass 
{
    private static EventOperations eventOperation = null;
    
    void SomeMethod()
    {
        if(true)
        {
            eventOperation = EventOperations.Cancel; // whatever value you set here, it'll be propagated to all the instances of some class.
        }
    }
}