簡體   English   中英

傳遞接口類型以強制轉換為參數

[英]Passing the Interface type for casting as parameter

我有一個使用泛型調用另一個函數的函數。
現在我想將內部函數的類型作為參數傳遞給外部函數:

void MyFunction()
{
    CallFunction<ISomeInterface>(); //  here ISomeInterface should be a parameter to MyFunction
}

我已經嘗試過<T>以及typeofType但是沒有成功。

編輯:嘗試:

void MyFunction<T>()

void MyFunction(Type type)

CallFunction<typeof(parameter)>();

您可以做的是使MyFunction泛型並將type參數傳遞給被調用的方法:

void MyFunction<T>()
{
    CallFunction<T>();
}

然后可以使用以下命令調用它:

MyFunction<ISomeInterface>();

編輯: CallFunction似乎對其類型參數有約束。 MyFunction需要具有相同的約束:

如果你有

CallFunction<T>() where T : class { /* .. */ }

然后

void MyFunction<T>() where T : class { /* .. */ }

您需要像這樣進行一些反思:

void Main()
{
    MyFunction(typeof(Foo));
}

void MyFunction(Type someType)
{
    var method =
        this
            .GetType()
            .GetMethod(
                "CallFunction",
                BindingFlags.Instance | BindingFlags.NonPublic)
            .MakeGenericMethod(someType);

    method.Invoke(this, null);
}

void CallFunction<T>()
{
    Console.WriteLine(typeof(T).Name);
}

public class Foo { }

這會將Foo輸出到控制台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM