通用类型的gcnew操作符 [英] gcnew operator for generic type
本文介绍了通用类型的gcnew操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下简单类
generic<typename T> where T:IDbConnection ref class CDbConnection
{
private:
IDbConnection^m_db;
ConnectionState^ m_originalConnState;
public:
CDbConnection();
bool Connect(String ^ connStr);
bool Exists(int id);
auto GetAllData(String^ tableStr);
~CDbConnection();
!CDbConnection();
};
这里是我的构造函数
generic<typename T> CDbConnection<T>::CDbConnection()
{
m_db=gcnew T();
m_originalConnState=m_db->State;
}
但是编译器抱怨< 1> gcnew T用于通用类型
<2> auto
键使用错误,因为函数期望返回类型
But the compiler complains <1> the gcnew T() can't be used for generic type
<2> auto
key in use is wrong as the function expects a trailing return type
推荐答案
为了实现通用性,必须将类定义更改为
In order to achieve genericity, you must change your class definition to
generic<typename T> where T:IDbConnection ref class CDbConnection
{
private:
T m_db;
ConnectionState^ m_originalConnState;
public:
CDbConnection();
bool Connect(String ^ connStr);
bool Exists(int id);
auto GetAllData(String^ tableStr);
~CDbConnection();
!CDbConnection();
};
由于您已经约束了 T
至少 IDbConnection
它不能是其他的。
然后你的构造函数
As you are already constraining your T
to be at least IDbConnection
it can't be anything else.
Then your constructor
generic<typename T> CDbConnection<T>::CDbConnection()
{
m_originalConnState=m_db.State;
}
应该像您预期的那样工作。
should work like you intended.
EDIT
似乎你不能声明一个泛型的引用。如果将对象分配给堆栈,它将工作。
请参见此条目。
It seems you cannot declare a reference to a generic. If you assign the object to the stack it will work. See this entry.
// C3229.cpp
// compile with: /clr /c
generic <class T>
ref class C {
T^ t; // C3229
};
// OK
generic <class T>
ref class D {
T u;
};
这篇关于通用类型的gcnew操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文