我根本找不到任何例子。
这是我目前正在做的事情:
public partial class RenameGroupPopupViewModel
{
private string _newGroupName;
public string NewGroupName
{
get => _newGroupName;
set => SetProperty(ref _newGroupName, value);
}
}
在 ObservableObject.cs 中有一个参数 validateValue 但我不知道或不明白如何使用它。
我想尝试使用 Func
这是该类的完整代码:
这是来自
的代码片段 /// <summary>
/// Sets the property.
/// </summary>
/// <returns><c>true</c>, if property was set, <c>false</c> otherwise.</returns>
/// <param name="backingStore">Backing store.</param>
/// <param name="value">Value.</param>
/// <param name="validateValue">Validates value.</param>
/// <param name="propertyName">Property name.</param>
/// <param name="onChanged">On changed.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
protected virtual bool SetProperty<T>(
ref T backingStore,
T value,
[CallerMemberName] string propertyName = "",
Action? onChanging = null,
Action? onChanged = null,
Func<T, T, bool>? validateValue = null)
{
// if value didn't change
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
// if value changed but didn't validate
if (validateValue != null && !validateValue(backingStore, value))
return false;
onChanging?.Invoke();
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
我知道我必须提供一个验证函数,但我不确定如何指定它,它应该是一种普通的方法还是委托(delegate)?这是我需要的功能:
private bool ValidateName(string groupName)
{
if (groupName == "default")
return false;
else
return true;
}
最佳答案
您调用的方法包含此子句:
// if value changed but didn't validate
if (validateValue != null && !validateValue(backingStore, value))
return false;
这是在调用 validateValue
传入的委托(delegate)。委托(delegate)有两个参数,类型均为 T
对于通用 SetProperty<T>()
方法,并返回一个 bool
, 其中false
意味着传递给委托(delegate)的值不符合调用方为委托(delegate)实现的任何标准。
请注意 backingStore
,这是属性的当前值,value
,这是分配给属性的新值,都传递给验证委托(delegate)。因此,委托(delegate)人可以根据需要自由使用其中一个或两者。
您选择的方法似乎只关心新分配的值。因此,您可以通过更改验证方法签名以接受两个参数并忽略第一个参数来传递适当的委托(delegate):
private bool ValidateName(string currentName, string newName)
{
if (newName == "default")
return false;
else
return true;
}
和
public string NewGroupName
{
get => _newGroupName;
set => SetProperty(ref _newGroupName, value, validateValue: ValidateName);
}
或者您可以保留您现在的方法,并将对它的调用包装在 lambda 表达式中:
public string NewGroupName
{
get => _newGroupName;
set => SetProperty(ref _newGroupName, value, validateValue: (_, newName) => ValidateName(newValue));
}
两者都可以。
注意命名参数的使用,因为 value
之间还有其他参数正在传递的参数和正在传递的委托(delegate)引用,您可能仍然不想指定。命名 validateValue
parameter 允许其他参数仍然被省略,从而导致它们的默认值按预期传递。
另请注意,在任何一种情况下,委托(delegate)实例 都是实际传递的内容。 C# 编译器自动将表达式(例如第一个示例中的“方法组名称”或第二个示例中的“lambda 表达式”)转换为使用提供的方法作为目标来实例化新委托(delegate)实例的代码委托(delegate),根据代码的上下文推断委托(delegate)类型(在此示例中,传递的实际委托(delegate)类型将是 Func<string, string, bool>
)。这种形式的 Lambda 表达式被编译为“匿名方法”。如果需要,您可以查找这些条款以获取更多信息。
关于c# - 任何人都可以向我解释如何使用 Func<T, T, bool> 吗? validateValue = null) Xamarin 社区工具包 ObservableObject 中的验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66450850/