代码之家  ›  专栏  ›  技术社区  ›  Kari

c#:检查“ref”参数是否来自静态变量

  •  0
  • Kari  · 技术社区  · 6 年前

    如果参数是静态变量,有没有办法从函数内部检查?

    这将帮助我防止任何打字错误的可能性 用户试图快速设置单例,但忘记声明自己的单例 instance 成员身份 static 在通过 ref

    // returns 'false' if failed, and the object will be destroyed.
    // Make sure to return from your own init-function if 'false'.
    public static bool TrySet_SingletonInstance<T>(this T c,  ref T instance) where T : Component {
    
        //if(instance is not static){ return false } //<--hoping for something like this
    
        if(instance != null){  
            /* cleanup then return */
            return false;  
        }
        instance = c;
        return true;
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   John Wu    6 年前

    单一的 ton),我们可以使用类型查找字段。在这种情况下,实际上根本不需要在引用中传递它。由于我们知道如何获取FieldInfo,我们可以通过反射判断它是否是静态的。

    public static bool TrySet_SingletonInstance<T>(this T c) where T : Component
    {
        //Find a static field of type T defined in class T 
        var target = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).SingleOrDefault(p => p.FieldType == typeof(T));
    
        //Not found; must not be static or public, or doesn't exist. Return false.
        if (target == null) return false;
    
        //Get existing value
        var oldValue = (T)target.GetValue(null);
    
        //Old value isn't null. Return false.
        if (oldValue != null) return false;
    
        //Set the value
        target.SetValue(null, c);
    
        //Success!
        return true;
    }
    

    用法:

    var c = new MySingleton();
    var ok = c.TrySet_SingletonInstance();
    Console.WriteLine(ok);
    

    请参见此处的工作示例: DotNetFiddle