C#:检查'ref'参数是否实际来自静态变量



是否有方法从函数内部检查参数是否为静态变量?

这将有助于我防止用户试图快速设置单例,但在通过ref将其提供给我们之前忘记将自己的instance成员声明为static时出现任何打字错误的可能性

这是我的功能:

// 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;
}

如果我们假设您的singleton类有一个且只有一个静态实例(这是有道理的,因为它是singleton(,我们可以使用类型来查找字段。在这种情况下,实际上根本不需要在对它的引用中传递它。既然我们知道如何获得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

最新更新