本文介绍了隐藏结构参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能隐藏用户在C#中参数的构造函数

Is it possible to hide the parameterless constructor from a user in c#

我要强迫他们总是使用带参数的构造函数

I want to force them to always use the constructor with parameters

例如。这个位置类

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;
    }
}

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

I only want users to be able to new up a Position by specifying the x and y coordinates

不过,参数的构造函数总是availiable

However, the parameterless constructor is ALWAYS availiable

我不能让它私有。甚至把它定义为公共

I cannot make it private. Or even define it as public

我已阅读本http://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net

但它没有真正帮助

如果这是不可能的 - 什么是检测,如果我传递的地位价值的最佳途径。

If this is not possible - what is the best way to detect if the Position I am being passed has values?

明确地检查每一个属性字段?有没有雨衣的方式?

Explicity checking each property field? Is there a slicker way?

感谢

推荐答案

没有,你不能做到这一点。正如你所说,类似的问题已经被问过 - 我认为答案是很清楚,你不能这样做

No, you can't do this. As you said, similar question has been asked before - and I thought the answer was fairly clear that you couldn't do it.

您的可以的create私人无参数的构造函数的结构,但不是在C#。但是,即使你这样做,它并没有真正帮助 - 因为你可以很容易地解决它:

You can create a private parameterless constructor for a struct, but not in C#. However, even if you do that it doesn't really help - because you can easily work around it:

MyStruct[] tmp = new MyStruct[1];
MyStruct gotcha = tmp[0];

这将是MYSTRUCT的默认值 - 全零的价值 - 而没有调用构造函数

That will be the default value of MyStruct - the "all zeroes" value - without ever calling a constructor.

您可以轻松地添加一个验证的方法来你的结构,并调用每次收到的一个作为参数,无可否认的。

You could easily add a Validate method to your struct and call that each time you received one as a parameter, admittedly.

这篇关于隐藏结构参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:25