相关疑难解决方法(0)

在struct上隐藏无参数构造函数

是否可以在c#中隐藏用户的无参数构造函数

我想强制他们总是使用带参数的构造函数

例如这个职业课程

public struct Position
{
    private readonly int _xposn;
    private readonly int _yposn;

    public int Xposn
    {
        get { return _xposn; }
    }

    public int Yposn
    {
        get { return _yposn; }
    }

    public Position(int xposn, int yposn)
    {
        _xposn = xposn;
        _yposn = yposn;
    }        
}
Run Code Online (Sandbox Code Playgroud)

我只希望用户能够通过指定x和y坐标来新建位置

但是,无参数构造函数始终可用

我不能把它私有化.甚至将其定义为公开

我已经读过这个 为什么我不能在.NET中为结构定义默认构造函数?

但它并没有真正的帮助

如果这是不可能的 - 检测我被传递的位置是否具有值的最佳方法是什么?

明确检查每个属性字段?有一种更光滑的方式吗?

谢谢

.net c# struct

26
推荐指数
2
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1

struct ×1