Вопрос

in .net there exist classes like RegistryKey that aren't static for example:

RegistryKey RK=Registry.LocalMachine;

the above class is not static (as far as I understand) yet it has no constructor for example

RegistryKey RK=new RegistryKey();

isn't valid (the registry key class has no constructors defined)

I searched the web and SO yet I couldn't find any information

when I write the following

class MyClass2
{
    protected MyClass2(int x)
    {
    }
}

I get MyClass2.MyClass2 is inaccessible due to it's protection level

what I really want to know is if there is no way other than making the constructor private how can there be different messages for classes like RegisteryKey and MyClass2 ?

Это было полезно?

Решение

RegistryKey has two private constructors with parameters. Probably the error message is because there isn't a default constructor RegistryKey(), because if you define a constructor with parameters, the implicit parameterless constructor isn't generated. Being them private, you don't see them.

Technically even abstract classes can't be built with new. You then could create a private derived class (or an internal derived class).

Другие советы

None of the classes below is static or abstract and you can still not create instance of ClassA because of the constructor is Internal (in this case). ClassB can of course create instance of ClassA as both the classes are part of same assembly and could return it to the caller.

public class ClassA 
{
   internal ClassA()
   {
       // Internal default constructor.
   }

   public void GetDateTime()
   {
       Console.WriteLine(DateTime.Now.ToString());
   }

}

public  class ClassB
{
    public ClassA GetClassA()
    {
        ClassA obj = new ClassA();
        return obj;
    }


}

ClassA instance is reachable via ClassB.

        ClassB objB = new ClassB();
        ClassA objA = objB.GetClassA();
        objA.GetDateTime();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top