C#generics – 可以用n个generics类型创建一个方法..?
我不认为这是可能的,但是这里……
我想添加可以处理generics的数字的方法。 例如 :
bool MyMethod() where T: Isomething { }
将适用于一种类型
bool MyMethod() where T: Isomething { }
将适用于两种类型
有没有办法处理n种类型 – 例如
bool MyMethod() where T: Isomething { }
我想这样做的原因是实现一个静态的nhibernate辅助方法,它可以从多个程序集加载 – 现在它适用于一个程序集。 我目前的方法如下所示:
public static ISessionFactory GetMySqlSessionFactory(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(); m.AutoMappings.Add(AutoMap.AssemblyOf().Conventions.Add); }) .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()
}
显然这不起作用我不是完全愚蠢,但我对generics不太热 – 有人可以证实这是不可能的:-) ..? 在您看来,实现这种效果最优雅的方式是什么?
否 – generics类型和方法的优点是基于每种类型/方法修复的。
这就是框架中存在所有不同的Action<...>
, Func<...>
和Tuple<...>
类型的原因。
偶尔这是一种耻辱,但它相对很少会受到影响,我怀疑各种各样的东西会变得更加复杂,可变的arity。
你似乎重复了牛顿曾经做过的同样的错误。 他有两只猫,一只较大,另一只较小。 他在门上打了两个洞,较大的洞用于较小的洞,较小的洞用于较小的猫洞。 实际上,他需要一个大洞来帮助这只猫。
为什么不创建一个可以处理所需类型的方法。
bool MyMethod() where T: Isomething { }
实际上我只是注意到了这个链接 – 我现在必须回家但是如果有效的话我可能会尝试这样的事情:
http://geekswithblogs.net/marcel/archive/2007/03/24/109722.aspx
我想如果我传入一个类型的数组并使用reflection循环这些类型,这将起作用。
正如其他人指定你做不到的:
bool MyMethod() where T: ISomething
但你可以这样做:
bool MyMethod(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(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(new SomethingA(), new SomethingB());
C#交互式窗口输出:
> MyMethod(a, b); Submission#0+SomethingA Submission#0+SomethingB > > MyMethod(new SomethingA(), new SomethingB()); Submission#0+SomethingA Submission#0+SomethingB
因此,您可以接收所需的类型(符合通用类型)并循环遍历它们并按照您指定的方式调用代码。 你也可以不使用generics,只需要参加params对象[]的事情; 但如果可以,我建议强烈输入。
如果有人看到这个,请告诉我,如果我离开基地或误解了这个问题……谢谢!