NOTE: I have re-written this post to be more helpful to users in the future with similar issues. Though it sticks relatively to the original posting.
I am currently updating a component to be part of a public API and would like to prevent certain properties from having specific values. More specifically, I have some integers that should never be less than zero.
I am already aware that throwing an exception in the set accessor of the property is a good way to get started with this venture, and that typically the publisher throws the exception and allows the subscriber to catch it.
private int x;
public int Y {
get { return x; }
set {
if (value < 0)
throw new ArgumentException();
else x = value;
}
}
However, I am unsure if Visual Studio will handle the exception and I would like to know if there is a set in stone, proper way to handle this issue. For example you have attribute tags that set the description, visibility, etc. Is there something similar for preventing values? Are there any ways to do this using metadata? I am looking for the right way to do this.
RESULT
Throwing an exception in the set accessor works just fine. Visual Studio catches the exception and displays a message box saying property value not is not valid. This will suffice and typical best practices can be followed in this case.
答案 0 :(得分:0)
use custom setter
public class Foo
{
int m_widget;
int Widget {set{
if(value == 42)
throw new ArgumentException("Invalid value");
m_widget = value;
} get { return m_widget;}
}
答案 1 :(得分:0)
public class CoolStuff
{
private int _SafeInteger {get;set;}
public int SafeInteger
{
get
{
return _SafeInteger;
}
set
{
if(value < 0)
{
throw new ArgumentException("SafeInteger must be greater than or equal to 0.");
}
else
{
_SafeInteger = value;
}
}
}
}