开发者

C# Generics and Constraints

If I have a generic constraint where C must be a struct:

class MyNum<C> where C : struct
{
    C a;
    public MyNum(C a)
    {
        this.a = a;
    }
}

struct myStruct
{
    public int a;
}

I understand that this compiles:

    myStruct n = new myStruct();
    n.a = 5;
    MyNum<myStruct> str = new MyNum<myStruct>(n);

But why would this compile. ¿Is number 5 a structure?

I thought by doing this:

int b = 5;

b would be of type int, but not type struct. I guess I´m missin开发者_StackOverflowg something here.

Also just to use the correct terminology:

int b = 5; 

Am I instantiating b? Creating an int instance? For some reason in my mind when I think of "instances" I think of reference types.

Here:

Car c1 = new Car(); 

Here I understand that I´m creating a Car instance or instantiating c1.


int is a struct.

Look at Int32 definition on MSDN


EDIT:

Doing:

 int i = 5;

as well as:

MyStruct m = new MyStruct();

you're creating a memory location as big as the necessary space to contain the struct.
The difference with reference types, is that variables m and i aren't references to those memory locations storing values, but they're basically "the value itself".

Infact when you do:

MyStruct m1 = new MyStruct();
MyStruct m2 = m1;

m2 doesn't represent the same memory location of m1, but the content of m1 is copied in a new location of memory represented by the variable m2


According to MSDN with a struct Type constraint, The type argument must be a value type. Any value type except Nullable can be specified.

And as diggEmAll mentioned already int is struct


Yes 5 is an int and int is a structure

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜