我有一个带有通用参数的方法,它根据运行时字符串值过滤值。它要么让值通过,要么返回 default();
public T Filter<T>(string target, string actual, T value)
{
bool isMatch = !string.IsNullOrEmpty(target)
&& !string.IsNullOrEmpty(actual)
&& target.ToUpper() == actual.ToUpper();
return isMatch ? value : default(T);
}
除 bool 值外,这对大多数情况都适用。当一个 boolean false 进来并且应该被过滤时,它返回为 false —— boolean 的 default() 。
因此,当传入 bool
时,我希望它执行的操作是返回 bool 值的倒数。如何从 T
到 bool
并返回返回类型 T
?
谢谢!
最佳答案
编辑: 我会使用带有默认参数的 dtb 答案。但是,如果您出于某种原因无法使用它,这是我的替代方案。
我会将匹配代码重构为一个新方法,并使用 bool 值的特定版本重载泛型。
public T Filter<T>(string target, string actual, T value)
{
return _match(target, actual) ? value : default(T);
}
public bool Filter(string target, string actual, bool value)
{
return _match(target, actual) ? value : !value;
}
private bool _match(string target, string actual)
{
return !string.IsNullOrEmpty(target)
&& !string.IsNullOrEmpty(actual)
&& string.Equals(target, actual, StringComparison.CurrentCultureIgnoreCase);
}
当第三个参数为 bool 值时,方法调用将解析为 bool 值版本。如果不是,它将解析为通用版本。
关于c# - 反转 bool 值的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18647801/