실행시에만 알려진 형식 인수로 일반 메서드 호출
이 질문에는 이미 답변이 있습니다.
편집하다:
물론 내 실제 코드는 정확히 이와 같지 않습니다. 나는 원하는 의사를 더 명확하게하기 위해 세미 의사 코드를 작성하려고했습니다.
대신 물건을 엉망으로 한 것처럼 보입니다.
그래서 실제로하고 싶은 것은 이것입니다 :
Method<Interface1>();
Method<Interface2>();
Method<Interface3>();
...
글쎄 ... 나는 아마도 반사를 사용하여 루프로 바꿀 수 있다고 생각했습니다. 그래서 질문은 : 어떻게합니까? 나는 성찰에 대한 지식 이 매우 얕습니다. 따라서 코드 예제가 좋을 것입니다.
시나리오는 다음과 같습니다.
public void Method<T>() where T : class
{}
public void AnotherMethod()
{
Assembly assembly = Assembly.GetExecutingAssembly();
var interfaces = from i in assembly.GetTypes()
where i.Namespace == "MyNamespace.Interface" // only interfaces stored here
select i;
foreach(var i in interfaces)
{
Method<i>(); // Get compile error here!
}
원본 게시물 :
안녕하세요!
네임 스페이스의 모든 인터페이스를 반복하여 다음과 같은 일반 메소드에 인수로 보냅니다.
public void Method<T>() where T : class
{}
public void AnotherMethod()
{
Assembly assembly = Assembly.GetExecutingAssembly();
var interfaces = from i in assembly.GetTypes()
where i.Namespace == "MyNamespace.Interface" // only interfaces stored here
select i;
foreach(var interface in interfaces)
{
Method<interface>(); // Get compile error here!
}
}
The error I get is "Type name expected, but local variable name found". If I try
...
foreach(var interface in interfaces)
{
Method<interface.MakeGenericType()>(); // Still get compile error here!
}
}
I get "Cannot apply operator '<' to operands of type 'method group' and 'System.Type'" Any idea on how to get around this problem?
EDIT: Okay, time for a short but complete program. The basic answer is as before:
- Find the "open" generic method with Type.GetMethod
- Make it generic using MakeGenericMethod
- Invoke it with Invoke
Here's some sample code. Note that I changed the query expression to dot notation - there's no point in using a query expression when you've basically just got a where clause.
using System;
using System.Linq;
using System.Reflection;
namespace Interfaces
{
interface IFoo {}
interface IBar {}
interface IBaz {}
}
public class Test
{
public static void CallMe<T>()
{
Console.WriteLine("typeof(T): {0}", typeof(T));
}
static void Main()
{
MethodInfo method = typeof(Test).GetMethod("CallMe");
var types = typeof(Test).Assembly.GetTypes()
.Where(t => t.Namespace == "Interfaces");
foreach (Type type in types)
{
MethodInfo genericMethod = method.MakeGenericMethod(type);
genericMethod.Invoke(null, null); // No target, no arguments
}
}
}
Original answer
Let's leave aside the obvious problems of calling a variable "interface" to start with.
You have to call it by reflection. The point of generics is to put more type checking at compile time. You don't know what the type is at compile-time - therefore you've got to use generics.
Get the generic method, and call MakeGenericMethod on it, then invoke it.
Is your interface type itself actually generic? I ask because you're calling MakeGenericType on it, but not passing in any type arguments... Are you trying to call
Method<MyNamespace.Interface<string>>(); // (Or whatever instead of string)
or
Method<MyNamespace.Interface>();
If it's the latter, you only need a call to MakeGenericMethod - not MakeGenericType.
'Programing' 카테고리의 다른 글
스파르타입니까? (0) | 2020.07.13 |
---|---|
암호화 / 암호 보호 기능이있는 SQLite (0) | 2020.07.13 |
ASP.NET 웹 API 인증 (0) | 2020.07.13 |
Bash에서 배열을 정렬하는 방법 (0) | 2020.07.12 |
스토리 보드에서 UIScrollView를 사용하는 방법 (0) | 2020.07.12 |