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
89 views
in Technique[技术] by (71.8m points)

c# - Create class for integer value identifier and new Number

I'm trying to pass some training tests with C#, but I've really stuck with this one

The task says: fix compiler error without changing of any string inside the Function(), create integer class to identify integer variable with specific name myIntIdentifier and output myNmb value

        public void Function()
        {                
             myIntIdentClass orgNumb = new Number { numbVal = 1, numbStr = "One"};
             int myNmb= orgNumb;

             Console.WriteLine(myNmb);
        }

Here is what I have tried:

    public class myIntIdentClass
    {
        public int numb { get; set; }

        public static implicit operator int(myIntIdentClass v)
        {
            throw new NotImplementedException();
        }
    }

    public class Number
    {
        private int intVal { get; set; }
        private string strVal { get; set; }
    }

but the new Number shows:

'Number' is inaccessible due to its protection level

question from:https://stackoverflow.com/questions/65942174/create-class-for-integer-value-identifier-and-new-number

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

1 Reply

0 votes
by (71.8m points)

You cannot initialize the class props because they are private.

here you are trying to init your class using one line initializer but your props are private, so you cannot access them.

 new Number { numbVal = 1, numbStr = "One"};

you can set the encapsulation level of the props in the Number class to public to fix this error.

   public class Number
    {
        public int intVal { get; set; }
        public string strVal { get; set; }
    }

By the way the convention for props is encapsulation level as public and naming in PascalCase.

And another error is that you are missing an implicit casting from Number to myIntIdentClass


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

...