[英]C# generics - possible to create a method with n Generic types..?
我不认为这是可能的,但是这里...
我想添加可以处理n个泛型的方法。 例如 :
bool<T> MyMethod() where T: Isomething
{
}
将适用于一种类型
bool<T,K> MyMethod() where T: Isomething
{
}
将适用于两种类型
是否可以使用n种类型-例如
bool<T[]> MyMethod() where T: Isomething
{
}
我要执行此操作的原因是要实现可以从多个程序集中加载的静态nhibernate帮助程序方法-现在,它对于一个程序集非常有用。 我当前的方法如下所示:
public static ISessionFactory GetMySqlSessionFactory<T>(string connectionString, bool BuildSchema)
{
//configuring is meant to be costly so just do it once for each db and store statically
if (!AllFactories.ContainsKey(connectionString))
{
var configuration =
Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString(connectionString)
.ShowSql() //for development/debug only..
.UseOuterJoin()
.QuerySubstitutions("true 1, false 0, yes 'Y', no 'N'"))
.Mappings(m =>
{
m.FluentMappings.AddFromAssemblyOf<T>();
m.AutoMappings.Add(AutoMap.AssemblyOf<T>().Conventions.Add<CascadeAll>);
})
.ExposeConfiguration(cfg =>
{
new SchemaExport(cfg)
.Create(BuildSchema, BuildSchema);
});
AllFactories[connectionString] = configuration.BuildSessionFactory();
}
return AllFactories[connectionString];
}
行:m.FluentMappings.AddFromAssemblyOf(),我想添加多个类型,例如
foreach(T in T[]){
m.FluentMappings.AddFromAssemblyOf<T>()
}
显然,这是行不通的,我不是很傻,但是我对泛型不是很热衷-有人可以确认这是不可能的:-) ..? 您认为实现此效果的最优雅方法是什么?
否-泛型类型和方法的种类固定在每种类型/方法的基础上。
这就是框架中存在所有不同的Action<...>
, Func<...>
和Tuple<...>
类型的原因。
有时候这是一种耻辱,但这种情况相对较少,我怀疑可变的Arity会使各种事情变得更加复杂。
实际上,我只是注意到了此链接-我现在必须回家,但是如果可以的话,我稍后可能会尝试这样的操作:
http://geekswithblogs.net/marcel/archive/2007/03/24/109722.aspx
我认为,如果我传入一个类型数组并通过反射遍历这些类型,那么它将起作用。
正如其他人指定的那样,您不能执行以下操作:
bool MyMethod<T[]>() where T: ISomething
但您可以:
bool MyMethod<T>(params T[] somethings) where T : ISomething
例如:
public interface ISomething { string Name { get; set; } }
public class SomethingA : ISomething { public string Name { get; set; } = nameof(SomethingA); }
public class SomethingB : ISomething { public string Name { get; set; } = nameof(SomethingB); }
void MyMethod<T>(params T[] somethings) where T : ISomething
{
foreach (var something in somethings)
{
if (something != null)
Console.WriteLine(something);
}
}
// Use it!
ISomething a = new SomethingA();
ISomething b = new SomethingB();
// You don't need to specify the type in this call since it can determine it itself.
MyMethod(a, b);
// If calling it like this though you do:
MyMethod<ISomething>(new SomethingA(), new SomethingB());
C#交互式窗口输出:
> MyMethod(a, b);
Submission#0+SomethingA
Submission#0+SomethingB
>
> MyMethod<ISomething>(new SomethingA(), new SomethingB());
Submission#0+SomethingA
Submission#0+SomethingB
因此,您可以输入想要的类型(符合通用类型)并遍历它们,然后像指定的那样调用代码。 您也不能使用泛型,而只能使用params object [] somes; 但如果可以的话,我强烈建议您输入。
如果有人看到此消息,请告诉我我是不是离开基地还是误解了这个问题……谢谢!
您似乎重复了牛顿曾经犯过的错误。 他有两只猫,一只大,另一只小。 他在门上开了两个洞,较大的洞为较大的洞,较小的洞为较小的猫。 实际上,他需要一个大洞来帮助两只猫。
为什么不创建一个可以处理所需类型的单一方法。
bool<T[]> MyMethod() where T: Isomething
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.