如何创建嵌套属性? C#

时间:2019-09-27 21:54:00

标签: c# properties

据我所知,在c#中似乎无法创建嵌套属性。

我想做的是:

Callout callout = new Callout();
callout.Font.Size = 200;

这是我目前拥有的代码

class Callout
{
     // nested properties
}

我知道如何创建属性,但是如何创建嵌套属性?

3 个答案:

答案 0 :(得分:3)

class Callout {
    public Font Font {get;} = new Font();
}
class Font {
    public int Size {get;set;}
}

答案 1 :(得分:1)

public class Callout {

    public Font Font {get;}
}

public struct Font {
    public Font(int size) {
        Size = size;
    }

    public int Size {get;}
}

答案 2 :(得分:1)

如果您真的不想实现单独的类或结构,这是一种执行要求的棘手方法。

注意:整!!=推荐

class Callout : Callout.IFont
{
    public interface IFont
    {
        int Size { get; set; }
    }
    protected int _fontSize = 0;

    int IFont.Size
    {
        get
        {
            return _fontSize;   
        }
        set
        {
            _fontSize = value;
        }
    }

    public IFont Font => this;
}


var callout = new Callout();
callout.Font.Size = 100;