开发者

Can I have a class within a class in C#

开发者 https://www.devze.com 2023-03-23 02:49 出处:网络
I have the following cl开发者_开发知识库ass: public class NoteLink { public IList<NoteLinkDetail> NoteLinkDetails

I have the following cl开发者_开发知识库ass:

public class NoteLink
{

    public IList<NoteLinkDetail> NoteLinkDetails
    {
        get { return _noteLinkDetails; }
    }
    private List<NoteLinkDetail> _noteLinkDetails = new List<NoteLinkDetail>();

    public NoteLink()
    {
        _noteLinkDetails = new List<NoteLinkDetail>();
    }

}

and then another class that's used just within the first class.

public class NoteLinkDetail
{
    public string L { get; set; }
    public string R { get; set; }
}

Is there anything I could do to optimize this. I DO need the second class as I use JSON to store the contents of NoteLinkDetail in a string. However is there such a thing as an inner class in C#? Any recommendation on how I could optimize this code? Thanks.


Yes, you can. Just nest it.

public class NoteLink
{
    // ...

    public NoteLink()
    {
        _noteLinkDetails = new List<NoteLinkDetail>();
    }

    public class NoteLinkDetail
    {
        public string L { get; set; }
        public string R { get; set; }
    }
}

Moreover, if it is not exposed outside the outer class, your inner class can even be private and stay invisible to outer class users.


Yes, C# allows nested classes.

C# nested classes are much more like nested classes in C++ than "inner classes" in Java. This link explains:

http://blogs.msdn.com/b/oldnewthing/archive/2006/08/01/685248.aspx


Sure; just declare the inner class from within the outer class

class NoteLink
{
    class NoteLinkDetail
    {

    }
}


Yes, you can have nested classes in C#

0

精彩评论

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