开发者

how to lmit values for a property of type string

I have a class with a property that saves as string. However the values for the property can only be from a list of values, similar to an enum. However this list of values is loaded from a lookup table,so it may vary, therefore it can not be an enum. I am talking to limit it in the type of the property and not validation nor in the GUI. Any hints of how to achieve that? Thanks in advance.

Edit: If I my list of values were known at design time, I would have an enum as the type for my property:

public enum MyValues{val1, val2, val3}

public class myClass
{
    ...
    public property MyValues myProp{get;set;}
}

...
myClass c1=new myClass();
c1.myProp=MyValues.val3;

However, as my values are loaded from a lookup table in the DB I cannot use enums. EDIT 2: I would like to have something like:

public class MyValue:string
{
    public MyValue(string Val):base(val){} //this doesn't exist
}
public class MyValues:List<MyValue>
{
     public static MyValues GetValues()
     {
         //load values from DB;
        //plus All

     }
     public static MyValue ValueAll{get{return new MyValue("All"开发者_StackOverflow社区)
}

public class myClass
{
    ...
    public property MyValue myProp{get;set;}
}

...
myClass c1=new myClass();
c1.myProp=MyValues.ValueAll;
//load combo with MyValues.GetValues();
c1.myProp = cboValues.SelectedValue;


Property setters are full-fledged methods, and you can execute any code that you like within them. For example,

private string myProperty;
private HashSet<string> validValues;

public string MyProperty
{
    get { return myProperty; }
    set
    {
         if(!validValues.Contains(value)) throw new ArgumentException();

         myProperty = value;
    }
}

This is obviously a simple (and incomplete) example, but it should demonstrate what you need to do: in your setter, somehow validate that the supplied value (available in the value parameter, which is implicit) is valid. If it isn't, throw an exception (ArgumentException is the example used here and is fine, or feel free to throw a more specific or meaningful exception). If it is, set the value.

Edit after Question Edit

The only real problem with your code is that you're trying to inherit from string, which is not allowed, though it's not really clear why you need to inherit from string. Make your property use MyValue as its type, bind cboValues to your list, then use (MyValue)cboValues.SelectedItem instead of SelectedValue to set your property.


You can do a value check in the property setter.


As an example:

using System.Collections.Generic;

class Foo
{
    HashSet<string> validBars = new HashSet<string>(){"Apple", "Orange", "Banana"};

    string bar = "Apple";
    public string Bar {
        get { return bar; }
        set {
            if(validBars.Contains(value)
                bar = value;
        }
    }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜