How to create a c# class that gives you usage like: ClassName.Property.Subproperty
I want to create a class so I can use it 开发者_StackOverflowlike this:
Website.Urls.User.Edit
Website.Urls.User.Add
Website.Urls.Content.List
How can I do this in c#? (they will return strings)
public class UserClass
{
public string Edit {get;set;}
public string Add {get;set;}
}
public class UrlsClass
{
public UserClass User {get;set;}
}
public class Website
{
public UrlsClass Urls {get;set;}
}
For what do you need that?
If the properties are classes, then you can access the properties of the referenced class. Some would argue that this violates the principle of information-hiding, but I think that somewhat depends on the case. For instance, in an ORM (object relational mapping), a property might be a class mapping a foreign key reference, and that's (possibly) a little better than some other circumstances.
Anway, this would not be a case for implicit properties. Use a declared private field for the property to reference, and check it for null before returning it. If null, then fill the property and return.
It seems to me that you should rethink your architecture as this deepy nested structure implies clumsy design. For further information, see the Law of Demeter.
精彩评论