简体   繁体   English

C#泛型-可以创建具有n个泛型类型的方法。

[英]C# generics - possible to create a method with n Generic types..?

I don't think this is possible but here goes... 我不认为这是可能的,但是这里...

I want to add method that can handle n numer of generics. 我想添加可以处理n个泛型的方法。 for example : 例如 :

bool<T> MyMethod() where T: Isomething
{
}

will work for one type 将适用于一种类型

bool<T,K> MyMethod() where T: Isomething
{
}

will work for two types 将适用于两种类型

Is there a way to work with n types - eg 是否可以使用n种类型-例如

bool<T[]> MyMethod() where T: Isomething
{
}

the reason I want to do this is to implement a static nhibernate helper method which can load from multiple assemblies - right now it works great for one assembly. 我要执行此操作的原因是要实现可以从多个程序集中加载的静态nhibernate帮助程序方法-现在,它对于一个程序集非常有用。 My current method is as shown below: 我当前的方法如下所示:

        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];
    }

Where the line: m.FluentMappings.AddFromAssemblyOf(), I would like to add multiple types eg 行:m.FluentMappings.AddFromAssemblyOf(),我想添加多个类型,例如

foreach(T in T[]){
   m.FluentMappings.AddFromAssemblyOf<T>()

} }

Obviously this couldn't work I'm not completely dumb but I am not so hot on generics - can someone confirm that this isn't possible :-) ..? 显然,这是行不通的,我不是很傻,但是我对泛型不是很热衷-有人可以确认这是不可能的:-) ..? What would be the most elegant way of achieving this effect in your opinion..? 您认为实现此效果的最优雅方法是什么?

No - the arity of generic types and methods is fixed on a per-type/method basis. 否-泛型类型和方法的种类固定在每种类型/方法的基础上。

That's why there are all the different Action<...> , Func<...> and Tuple<...> types in the framework. 这就是框架中存在所有不同的Action<...>Func<...>Tuple<...>类型的原因。

Occasionally that's a shame, but it gets in the way relatively rarely, and I suspect all kinds of things would be a lot more complicated with variable arity. 有时候这是一种耻辱,但这种情况相对较少,我怀疑可变的Arity会使各种事情变得更加复杂。

Actually I just noticed this link - I have to go home now but I might try something like this later if it works: 实际上,我只是注意到了此链接-我现在必须回家,但是如果可以的话,我稍后可能会尝试这样的操作:

http://geekswithblogs.net/marcel/archive/2007/03/24/109722.aspx http://geekswithblogs.net/marcel/archive/2007/03/24/109722.aspx

I think if I passed in an array of types and looped through the types with reflection this would work. 我认为,如果我传入一个类型数组并通过反射遍历这些类型,那么它将起作用。

As others have specified you cannot do: 正如其他人指定的那样,您不能执行以下操作:

bool MyMethod<T[]>() where T: ISomething

but you CAN do: 但您可以:

bool MyMethod<T>(params T[] somethings) where T : ISomething

For instance: 例如:

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# Interactive Window Output: C#交互式窗口输出:

> MyMethod(a, b);
Submission#0+SomethingA
Submission#0+SomethingB
> 
> MyMethod<ISomething>(new SomethingA(), new SomethingB());
Submission#0+SomethingA
Submission#0+SomethingB

So, you could take in your types that you want (that conform to the generic) and loop through them and call your code like you specified. 因此,您可以输入想要的类型(符合通用类型)并遍历它们,然后像​​指定的那样调用代码。 You could also NOT use generics and just take in params object[] somethings; 您也不能使用泛型,而只能使用params object [] somes; but I'd recommend strongly typing it if you can. 但如果可以的话,我强烈建议您输入。

If anyone sees this please let me know if I'm way off base or misunderstood the question... Thanks! 如果有人看到此消息,请告诉我我是不是离开基地还是误解了这个问题……谢谢!

you seem to repeat the same mistake that newton once did perhaps. 您似乎重复了牛顿曾经犯过的错误。 He has two cats one was bigger and the other was smaller. 他有两只猫,一只大,另一只小。 He made two holes in door, bigger hole for the bigger one and smaller one for smaller cat. 他在门上开了两个洞,较大的洞为较大的洞,较小的洞为较小的猫。 Where as actually he needed one big hole to assist both the cat. 实际上,他需要一个大洞来帮助两只猫。

Why don't you create one single method that can deal with as many as types you want.. 为什么不创建一个可以处理所需类型的单一方法。

bool<T[]> MyMethod() where T: Isomething
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM