开发者

An inaccessible class. VS2010

开发者 https://www.devze.com 2022-12-27 08:30 出处:网络
I realy dont know what the problem is with VS2010. I created a class, and when I\'m tryingcreate an exemplar of the class I get an error: \"Errorxxx is inaccessible due to its protection level.

I realy dont know what the problem is with VS2010. I created a class, and when I'm trying create an exemplar of the class I get an error: "Error xxx is inaccessible due to its protection level.

Example:

public class Person
{
    Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
    p开发者_StackOverflow中文版ublic string name;
    public int age;

}

class Program
{
    static void Main(string[] args)
    {

        Person ps = new Person("Jack", 19);
    }
}


Try adding the public keywork to the Person constructor:

public Person(string name, int age)


You need to make your constructor public:

public Person(string name, int age)
{
    ...

You may ask, why aren't constructors public by default? What's the point of a class you can't instantiate via its constructor? Well, it can be useful if you want a class that can only be instantiated via factory methods, eg.

public class Person
{
    public static Person makePerson(string name, int age)
    {
        ...

The factory method, being a member of the Person class, can access the non-public constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消