How to group properties in c#?
I am not sure if I phrased the question correctly, but this is what I am trying to do.
I am writing test framework for a program that takes a set of args. I am developing a public class to deal with operations regarding these args. So that user can use like,
Load(SampleProgram.CommandArgs args)
{}
public class CommandArgs
{
public string Arg1
{
get; set;
}
public string Arg2
{
get; set;
}
public string Arg3
{
get; set;
}
public string Parsedvalue
{
get; set;
}
//......and so on..
}
My problem is that in these args, Arg2 and Arg3 belong a type and user might need to change the开发者_JAVA百科m later, even though the rest of args might not changes. So I moved the arg2 and arg3 into a seperate class and I want CommandArgs class to reuse it. How do I do this?
I tried this
public class CommandArgs
{
private GroupedCommandArgs grpargs = null;
public string Arg1
{
get; set;
}
//......and so on..
}
//In constructor..
grpargs = new GroupedCommandArgs(arg2, arg3);
This works so that if user wants to change arg2
, he or she can write,
CommandArgs.GroupedCommandArgs.arg2 = "something";
But, what I also need is that each time arg2
or arg3
changes, I need to update some of the properties like Parsedvalue
.
How do I do this? My code is in c#.
Thanks
Use inheritance. Include the common arguments in the base CommandArgs
class and for cases with exctra properties create subclasses like AdditionalCommandArgs
.
class CommandArgs
{
public string Arg1 { get; set; }
public virtual string ParsedValue
{
get
{
return "Arg1: " + Arg1;
}
}
}
class AdditionalCommandArgs : CommandArgs
{
public string Arg2 { get; set; }
public string Arg3 { get; set; }
public override string ParsedValue
{
get
{
return base.ParsedValue + "\r\n" +
"Arg2: " + Arg2 + "\r\n" +
"Arg3: " + Arg3;
}
}
}
If the main thing you want is to allow your code to intercept the change in value of Arg2, Arg3, etc., and then fire off a change to a different property, you would probably want to implement INotifyPropertyChanged
Check out the example here: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
And then, in your own custom NotifyPropertyChanged method, make sure to update Parsedvalue as you wish.
精彩评论