Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

c# - Hide parameterless constructor on struct

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

e.g. this Position struct

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

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

However, the parameterless constructor is ALWAYS available.

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

I have read this: Why can't I define a default constructor for a struct in .NET?

but it doesn't really help.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...