제네릭 메서드를 노출하는 제네릭 클래스가 있습니다. 이 메서드는 일반 개체의 인스턴스를 매개 변수로 받고이 인스턴스를 수정합니다.
예제 클래스 :
public class GenericClass<T>
{
public T GenericMethod(T obj)
{
// modify the object in some (arbitrary) way
IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeof(string))
{
field.SetValue(obj, "This field's string value was modified");
}
}
return obj;
}
}
유형 (abc)이있는 경우 :
public class abc
{
public string a;
public string b;
public int c;
}
이 메서드를 다음과 같이 호출 할 수 있습니다.
GenericClass<abc> myGeneric = new GenericClass<abc>();
var myObject = myGeneric.GenericMethod(new abc());
//Confirm success by printing one of the fields
Console.Writeline(((abc)myObject).a);
이제 내 실제 질문 :
위의 abc 유형과 달리 런타임에만 알려진 유형을 사용하여 동일한 Generic 메서드를 어떻게 호출 할 수 있습니까? 또한 위의 abc에서했던 것처럼 GenericMethod에 전달할 때 이것을 인스턴스화하고 싶습니다.
예 (나는 이것이 완전히 틀렸다는 것을 안다)
Type MyType;
GenericClass<MyType> myGeneric = new GenericClass<MyType>();
var myObject = myGeneric.GenericMethod(new MyType());
알 수없는 유형의 성공은 존재하지 않을 수있는 "a"필드를 인쇄하여 확인할 수 없기 때문에 모든 문자열 필드의 값을 인쇄 할 수 있지만 이것은 질문의 범위를 벗어납니다.
질문에 답하려면 :
var type = typeof(abc);
object instanceToModify = new abc();
var typeToCreate = typeof(GenericClass<>).MakeGenericType(type);
var methodToCall = typeToCreate.GetMethod("GenericMethod");
var genericClassInstance = Activator.CreateInstance(typeToCreate);
methodToCall.Invoke(genericClassInstance, new[] { instanceToModify });
그러나:
유형이 런타임에만 알려진 경우 인스턴스는 object
또는로 선언 된 변수에서 처리되어야합니다 dynamic
. 이 경우 메서드 서명을 다음과 같이 변경할 수 있습니다.
public object GenericMethod(object obj)
{
// modify the object in some (arbitrary) way
IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
foreach (var field in fields)
{
if (field.FieldType == typeof(string))
{
field.SetValue(obj, "This field's string value was modified");
}
}
return obj;
}
일반 클래스 / 메소드가 필요하지 않습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다