Disallow calling public constructors other than XML serializer

Possible duplicate:
Why the XML-Serializable class needs a parameterless constructor

Does anyone know if it is possible to prevent a public constructor from being called outside the assembly range?

What I'm doing is a class library that has classes that are serializable by XML. These classes do not make sense if they are designed without setting various properties, so I want to prevent this condition.

I am wondering if there is a way to stop someone from calling my public constructor and keeping it there only for serialization?

+3
source share
3 answers

, , .

public foo() {
  this.bar = -1;
}

public foo(int bar) {
  this.bar = bar;
}

/ , Factory, .

+1

, , , , , getInstance , getInstance. getInstance, , .

0

, , :

if (Assembly.GetCallingAssembly().GetName().Name == "Forbidden.Assembly")
{
    throw new Exception(...);
}
0

Source: https://habr.com/ru/post/1712665/


All Articles