Is there an Integer class in C #?

We have a class Integerin JAVA, but I could not find an equivalent class in C #? Does C # have an equivalent? If not, how do I get JAVA class behavior Integerin C #?

Why do I need it?

This is because I'm trying to port JAVA code to C # code. If there is an equivalent way, then code migration will be easier. In addon, I need to save links Integer, and I don’t think I can create a link intor Int32.

+4
source share
7 answers

C # has a unified type system, so it intcan be implicitly placed in a link object. The only reason why it Integerexists in Java is that it can be converted to a reference to an object and stored in links that will be used in other container classes.

Since C # can do this without another type, there is no corresponding class for Integer.

+5
source

- . , Integer, (#, , . ), - . , , Int32 int. , , -:

    public class Integer
    {
        public int Value { get; set; }


        public Integer() { }
        public Integer( int value ) { Value = value; }


        // Custom cast from "int":
        public static implicit operator Integer( Int32 x ) { return new Integer( x ); }

        // Custom cast to "int":
        public static implicit operator Int32( Integer x ) { return x.Value; }


        public override string ToString()
        {
            return string.Format( "Integer({0})", Value );
        }
    }
+2

# , . object, . - - . Java , int Integer. # int Int32.

, , . int (.. int.whatever()), .NET- Javian Integer.

+1

Nullable , , , . :

static void Main(string[] args)
{
    int? x = 1;
    Foo(ref x);
    Console.WriteLine(x);//Writes 2
}

private static void Foo(ref int? y)
{
    y += 1;
    var l = new List<int?>();
    l.Add(y);
    l[0] += 1;//This does not affect the value of x devlared in Main
    Console.WriteLine(l[0]);//Writes 3
    Console.WriteLine(y);//writes 2
    Foo2(l);
}

private static void Foo2(List<int?> l)
{
    l[0] += 1;
    Console.WriteLine(l[0]);//writes 4
}

/ , , :

public class MyType<T>
{
    public T Value { get; set; }
    public MyType() : this(default(T))
    {}
    public MyType(T val)
    {
        Value = val;
    }

    public override string ToString()
    {
        return this.Value.ToString();
    }
}
static void Main(string[] args)
{
    var x = new MyType<int>(1);
    Foo(x);
    Console.WriteLine(x);//Writes 4
}

private static void Foo(MyType<int> y)
{
    y.Value += 1;
    var l = new List<MyType<int>>();
    l.Add(y);
    l[0].Value += 1;//This does affect the value of x devlared in Main
    Console.WriteLine(l[0]);//Writes 3
    Console.WriteLine(y);//writes 3
    Foo2(l);
}

private static void Foo2(List<MyType<int>> l)
{
    l[0].Value += 1;
    Console.WriteLine(l[0]);//writes 4
}
+1

Integer, Int32.

0

, Java Integer ( ), , null. # , int var = null # ( Java). , , / . null - . Integer.

0

All Articles