2013-09-25 2 views
-1

를 가지는 형태의 배열을 사용하는 앞으로 더 많은 유형에 대해 동일한 코드를 실행해야합니다.은 어떻게 아래의 C# 코드를 리팩토링 할 제네릭

+1

당신이 당신의 예제를 변경하여 주시겠습니까? 네가 뭘하려고하는지 전혀 모르겠다. –

+2

이 질문에 대한 답변을 생각합니다 : http://stackoverflow.com/questions/2107845/generics-in-c-using-type-of-a-variable-as-parameter –

답변

2

컴파일 타임에 유형이 무엇인지 모르는 경우 제네릭을 사용하는 것이 중요하지 않습니다.

SomeMethod(Type t){/*do some stuff here*/} 

과 코멘트에 @Florian 미군 병사에 의해 주어진 링크에 모습을 가지고 :
는 다음과 같이 뭔가 방법 서명을 변경하는 코드를 리팩토링.

0

공통 기본 유형을 상속 한 모든 유형의 목록을 자동으로 가져 오려면 리플렉션을 사용합니다. 서로 다른 종류의 무리에 정적 속성을 설정합니다 정적 방법에 대한 일 처리하는 것처럼 말했다

var assembly = Assembly.GetAssembly(typeof(SomeBaseClass)); 
var types = assembly.GetTypes().Where(type => typeof(SomeBaseClass).IsAssignableFrom(type)); 

이 보이는 : 그것은처럼 간단합니다. 을 사용할 수 있지만 전역 상태 (기본적으로 정적 속성)에 의존하지 않는이 문제에 대한 더 나은 접근 방법을 취하는 것이 훨씬 낫습니다.

0

MethodInfo이면 리플렉션을 통해 일반 메소드를 호출 할 수 있습니다.

먼저 MethodInfoMethodInfo MakeGenericMethod(params Type[] typeArguments)을 메서드의 각 제네릭 형식 인수에 대해 하나씩 호출합니다.

는 다음 순서로 메소드의 인수를 포함하는 객체의 결과 MethodInfoobject Invoke(object obj, object[] parameters) (그것이 static 방법 인 경우 또는 null) 당신이에서 호출 방법을 원하는 개체의 인스턴스 및 배열 호출합니다.

여기 컴파일, 실행 등의 작업을 위해 수정 된 C# 코드가 있습니다. Example1()이 첫 번째 코드 스 니펫입니다. Example2() 두 번째 코드 스 니펫에서 수행 할 작업을 수행합니다.

public class SomeBaseClass { 
    public string someProperty { 
     set { 
      Console.WriteLine(string.Format("someProperty called on {0} with {1}", this, value)); 
     } 
    } 
} 

public class Foo : SomeBaseClass { 
} 

public class Bar : SomeBaseClass { 
} 

public class Baz : SomeBaseClass { 
} 

public static class SomeMethods { 
    public static T SomeMethod<T>() where T : SomeBaseClass, new() { 
     return new T(); 
    } 
} 

class Program 
{ 
    public static void Example1() { 
     string someValue = "called from Example1"; 

     SomeMethods.SomeMethod<Foo>().someProperty = someValue; 
     SomeMethods.SomeMethod<Bar>().someProperty = someValue; 
     SomeMethods.SomeMethod<Baz>().someProperty = someValue; 
    } 

    public static void Example2() { 
     string someValue = "called from Example2"; 

     Type[] types = new Type[]{ 
      typeof(Foo), typeof(Bar), typeof(Baz), //... 
     }; 
     foreach (Type type in types) { 
      // Here's how: 
      System.Reflection.MethodInfo genericMethodInfo = typeof(SomeMethods).GetMethod("SomeMethod"); 
      System.Reflection.MethodInfo methodInfoForType = genericMethodInfo.MakeGenericMethod(type); 
      var someBase = (SomeBaseClass) methodInfoForType.Invoke(null, new object[] { }); 
      someBase.someProperty = someValue; 
     } 
    } 

    static void Main(string[] args) 
    { 
     Console.WriteLine("Example1"); 
     Example1(); 

     Console.WriteLine("Example2"); 
     Example2(); 

     Console.ReadKey(); 
    } 
} 

다음은 프로그램의 출력입니다 :

Example1 
someProperty called on ConsoleApplication1.Foo with called from Example1 
someProperty called on ConsoleApplication1.Bar with called from Example1 
someProperty called on ConsoleApplication1.Baz with called from Example1 
Example2 
someProperty called on ConsoleApplication1.Foo with called from Example2 
someProperty called on ConsoleApplication1.Bar with called from Example2 
someProperty called on ConsoleApplication1.Baz with called from Example2