什么是C#/ CLI的等效于C#的默认值(T)?

时间:2022-05-31 05:35:04

I'm working with some C++/CLI code (new syntax) and am trying to declare a generic type and want to set a member variable to it's default.

我正在使用一些C ++ / CLI代码(新语法)并尝试声明泛型类型,并希望将成员变量设置为默认值。

In C#:

class Class<T>
{ 
    T member = default(T);
}

What's the equivalent in CLI?

什么是CLI中的等价物?

generic<typename T> public ref class Class 
{
public:
    Class() : member(default(T))  // <-- no worky
    {
    }    
private:
        T member;
};

2 个解决方案

#1


11  

Interestingly enough the syntax makes it looks like this: T(). It does require the addition of a copy constructor.

有趣的是,语法使它看起来像这样:T()。它确实需要添加一个复制构造函数。

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(T())  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

Edit DOH This works too (been in C# land for so long I forgot that NULL and 0 are the same thing in C++, hence no need for different value and reference type default values):

编辑DOH这也有效(在C#land中已经很久了,我忘了在C ++中NULL和0是一样的,因此不需要不同的值和引用类型默认值):

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(0)  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

#2


1  

But isn't the private member already initialized with the default constructor?

但是私有成员是不是已经使用默认构造函数初始化了?

#1


11  

Interestingly enough the syntax makes it looks like this: T(). It does require the addition of a copy constructor.

有趣的是,语法使它看起来像这样:T()。它确实需要添加一个复制构造函数。

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(T())  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

Edit DOH This works too (been in C# land for so long I forgot that NULL and 0 are the same thing in C++, hence no need for different value and reference type default values):

编辑DOH这也有效(在C#land中已经很久了,我忘了在C ++中NULL和0是一样的,因此不需要不同的值和引用类型默认值):

generic<typename T> 
    public ref class Class 
{
public:
    Class() : member(0)  
    {
    } 

    Class(Class^ c)
    {
        member = c->member;
    }

private:
    T member;
};

#2


1  

But isn't the private member already initialized with the default constructor?

但是私有成员是不是已经使用默认构造函数初始化了?