C# 如何检查此工厂创建的错误<;T>;使用带参数的激活器的方法?
在这段代码中调用activator之前,我不确定是否/如何检查构造函数是否确实存在(未测试,因此可能有bug,但希望意图是明确的) 就好像我想要一个模板约束,上面写着“其中T有一个带签名S的构造函数”C# 如何检查此工厂创建的错误<;T>;使用带参数的激活器的方法?,c#,reflection,factory,C#,Reflection,Factory,在这段代码中调用activator之前,我不确定是否/如何检查构造函数是否确实存在(未测试,因此可能有bug,但希望意图是明确的) 就好像我想要一个模板约束,上面写着“其中T有一个带签名S的构造函数” 公共类EntityContainerFactory { 公共EntityContainerFactory(字符串sqlServerName、字符串databaseName、字符串元数据) :这(sqlServerName、databaseName、元数据,“System.Data.EntityCl
公共类EntityContainerFactory
{
公共EntityContainerFactory(字符串sqlServerName、字符串databaseName、字符串元数据)
:这(sqlServerName、databaseName、元数据,“System.Data.EntityClient”)
{
}
公共EntityContainerFactory(字符串sqlServerName、字符串databaseName、字符串元数据、字符串dataProviderName)
{
SqlServerName=SqlServerName;
DatabaseName=数据库名称;
元数据=元数据;
DataProviderName=DataProviderName;
}
//-->有没有办法检查T是否
//接受实体连接的构造函数?
公共文件不能创建()
{
return(T)Activator.CreateInstance(typeof(T),CreateEntityConnection());
}
EntityConnection CreateEntityConnection()
{
SqlConnectionStringBuilder sqlBuilder=新的SqlConnectionStringBuilder();
sqlBuilder.DataSource=SqlServerName;
sqlBuilder.InitialCatalog=数据库名称;
sqlBuilder.IntegratedSecurity=true;
EntityConnectionStringBuilder entityBuilder=新EntityConnectionStringBuilder();
entityBuilder.Provider=DataProviderName;
entityBuilder.ProviderConnectionString=sqlBuilder.ToString();
元数据=元数据;
返回新的EntityConnection(entityBuilder.ConnectionString);
}
公共字符串数据库名{get;set;}
公共字符串SqlServerName{get;set;}
公共字符串DataProviderName{get;set;}
私有字符串元数据;
公共字符串元数据
{
得到
{
字符串结果;
如果(!this.metaData.StartsWith(“res://”))
{
result=string.Format(@“res://*/{0}.csdl|res://*/{0}.ssdl | res://*/{0}.msl”,this.metaData);
}
其他的
{
结果=this.metaData;
}
返回结果;
}
设置
{
this.metaData=值;
}
}
}
不,您不能-唯一可用的与构造函数相关的通用约束是new()
,它需要无参数构造函数
一个选项是要求工厂代理:
public T Create<T>(Func<EntityConnection, T> factory)
{
return factory(CreateEntityConnection());
}
或任何其他将构建适当对象的内容。它更灵活、更安全,性能也更好。(无可否认,后者可能无关紧要……您是否考虑过使用接口而不是工厂?你可以得到更好的结果,而且你不会遇到这样的问题 无论如何:
where T : new()
仅适用于无参数构造函数。当具有该约束时,可以执行以下操作,而无需反射:
T obj = new T();
你必须手动检查
ConstructorInfo ctor = typeof(T).GetConstructor(new Type[] { EntityConnection });
if (ctor == null)
{
// Handle an unwanted type.
}
else
{
return (T)ctor.Invoke(entityConnection);
}
搜索其参数与
指定数组中的类型
请花点时间粘贴相关代码,而不是整个块或整个类。
T obj = new T();
ConstructorInfo ctor = typeof(T).GetConstructor(new Type[] { EntityConnection });
if (ctor == null)
{
// Handle an unwanted type.
}
else
{
return (T)ctor.Invoke(entityConnection);
}