English 中文(简体)
是否有办法将未知的类型量转至C#的通用方法?
原标题:is there a way to pass unknown amount of types to generic method in C#?

我有办法

void InitAndLoadTables(DbConnection cnctn, Dictionary<string, DbTableLoadParameters> tableNamesAndParameters)

字典可以有一定数量的表格。 每张表格对应一个类别。

当我通过所有表格检索时,我要说通用方法。

public void Init<T>(string tableName)

所有表格。 我试图将DbTableLoadPara计作为财产的那类财产列为一类。

Type ObjectType { get; set; }

并且使用“Init”一词。 这并不可行。 甚至有可能这样做? 如果表数固定下来,我可能会使InitAndLoadTables等通用表格成为可能。

InitAndLoadTables<T, K, V>

but it isn t. So is only possibility to call Init elsewhere like

Init<Orders>("Orders");

附录

最佳回答

不能将任意数目的类型论点采用通用方法,因为通用方法总是有固定数目的类型论点。

然而,你似乎甚至不需要。 有一种方法可以称作一种通用方法,其操作时间为人所知,但这涉及思考,它像你所回的

class Program
{
    static void Main(string[] args)
    {
        var myobj = new MyClass();

        // Call MyClass.Init<Orders>
        CallMyClassInit(typeof(Orders), "tableOrders");

        // Call Init<string>
        CallMyClassInit(typeof(string), "tableString");
    }

    static void CallMyClassInit(MyClass obj, Type type, string tableName)
    {
        typeof(MyClass)
            .GetMethod("Init")
            .MakeGenericMethod(type)
            .Invoke(obj, new object[] { tableName });
    }
}

class Orders { }

class MyClass
{
    public void Init<T>(string tableName)
    {
        Console.WriteLine("I was called with type " + typeof(T) + " for table " + tableName);
    }
}

Output:

I was called with type ConsoleApplication1.Orders for table tableOrders
I was called with type System.String for table tableString
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签