C# 当name为空时该怎么办代码被卡住了
当name为空时该怎么办代码停留在name=value处…不显示消息。 该怎么办?像这样试试C# 当name为空时该怎么办代码被卡住了,c#,C#,当name为空时该怎么办代码停留在name=value处…不显示消息。 该怎么办?像这样试试 public string Name { get { return name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("Name can not
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Name can not be empty");
name = value;
NotifyPropertyChanged();
}
}
如果您确实需要在name为null或空的情况下停止应用程序的执行,那么无论如何,在property setter中抛出一个异常。这不是“禁止的”。。。但在大多数情况下,我会将属性的验证放在其他地方 这是因为如果你抛出了一个异常,那么事情可能会爆炸,或者你可能会“卡住”,正如你所说的那样。另外,如果您需要在不同的场景中重用您的模型,其中属性相同,但名称可能为空,那么您会怎么做 我不知道您的场景是否涉及UI,但您可以使用ValidationRules检查属性的有效性,并通过UI绑定向用户提供提示 假设您有一个只包含名称和年龄属性的简单用户模型
public string Name
{
get
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Name can not be empty");
}
return name;
}
set { name = value; }
}
现在,您要检查是的,名称实际上不是null或空字符串。然后您可以创建简单的验证规则来检查这一点
public class User : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
private int _age;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged(); }
}
public int Age
{
get { return _age; }
set { _age = value; OnPropertyChanged(); }
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
现在,当这些都准备好了,并且在DataContext中有User类型的实例时,您可以在UI端使用用户输入和规则(假设它是WPF),如下所示
无效值!
这将为您提供以下关于有效输入的信息
在无效输入上执行以下操作
你可以在get{}中检查它。你说的“卡住”是什么意思?你想发生什么?你说的卡住是什么意思?您指的是异常发生后的调试吗?当为Name指定null或空字符串时,您期望得到什么?您不想看到异常?您可能应该根据需要使用一些业务逻辑来验证对象或对象属性,而不是在set或get中进行验证。请参见数据注释:
public class NameLengthRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string name = value as string;
return string.IsNullOrWhiteSpace(name) ? new ValidationResult(false, "Name can't be empty") : new ValidationResult(true, null);
}
}
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<AdornedElementPlaceholder/>
<TextBlock Foreground="Red">Invalid value!</TextBlock>
</DockPanel>
</ControlTemplate>
<Style x:Key="validationError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}" Style="{StaticResource validationError}" Margin="150">
<TextBox.Text>
<Binding Path="User.Name" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:NameLengthRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Grid>