gpt4 book ai didi

c# - 为什么密封类不允许是泛型类型参数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:40 24 4
gpt4 key购买 nike

我有:

public abstract class DbManager<ConnectionType>
where ConnectionType : class, IDbConnection, new() {...}

现在我分别有:

public class Db2Manager : DbManager<iDB2Connection>      // OK, NO problem
public class OleDbManager : DbManager<OleDbConnection> // OK, NO problem
public class SqlServerManager : DbManager<SqlConnection> // OK, NO problem
public class SsasManager : DbManager<AdomdConnection> // NOK, YES, a PROBLEM!

这是为什么?因为在命名空间 Microsoft.AnalysisServices.AdomdClient 中我们有一个密封类:

// Assembly Microsoft.AnalysisServices.AdomdClient.dll, v2.0.50727
using System;
using System.ComponentModel;
using System.Data;

namespace Microsoft.AnalysisServices.AdomdClient
{
public sealed class AdomdConnection : Component, IDbConnection,
IDisposable, ICloneable
{
public AdomdConnection();

a) 为什么限制使用密封类作为泛型参数(!参数,而不是约束!)?
b) 如何解决这个问题?
c*) 密封该类是个好主意吗?

附言。也许您有很多理由认为这个通用 DbManager 不是一个好主意,但是,无论如何,我只想了解是否有可能在通用参数中解决这个密封类...谢谢!

PPS。错误信息:

'Microsoft.AnalysisServices.AdomdClient.AdomdConnection' must be a non-abstract type with a public parameterless constructor in order to use it as parameter in the generic type or method.

另一条错误消息指定:

The type 'Microsoft.AnalysisServices.AdomdClient.AdomdConnection' cannot be used as type parameter in the generic type or method there is no boxing conversion or type parameter conversion from 'Microsoft.AnalysisServices.AdomdClient.AdomdConnection' to 'System.Data.IDbConnection'

AdomdConnection 有一个无参数公共(public)构造函数。

最佳答案

我相信密封类没有这样的限制。以下代码编译正常,因此可能还有其他问题。

public abstract class DbManager<T> where T : class, IDbConnection, new()
{
}

public class ConcreteDbManagerUsingSealedClass : DbManager<MySealedConnection>
{
}

public sealed class MySealedConnection : IDbConnection
{
public IDbTransaction BeginTransaction(IsolationLevel il)
{
throw new NotImplementedException();
}

public IDbTransaction BeginTransaction()
{
throw new NotImplementedException();
}

public void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}

public void Close()
{
throw new NotImplementedException();
}

public string ConnectionString
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

public int ConnectionTimeout
{
get { throw new NotImplementedException(); }
}

public IDbCommand CreateCommand()
{
throw new NotImplementedException();
}

public string Database
{
get { throw new NotImplementedException(); }
}

public void Open()
{
throw new NotImplementedException();
}

public ConnectionState State
{
get { throw new NotImplementedException(); }
}

public void Dispose()
{
throw new NotImplementedException();
}
}

关于c# - 为什么密封类不允许是泛型类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com