2014-10-31 5 views
1

사전을 사용하는 메서드를 재정의합니다. 참고 :이 질문은 잠재적 인 복제본과 약간 다릅니다 ... 그리고이 답변은 작동합니다 - 투표하기 전에 두 가지를 모두 읽어보십시오 :). -기본 형식이 기본 인

우리는 값에 대한 공통 기본 유형이 두 사전이 있습니다 상속이 작동 할 수있는 방법

// Three classes 
class BaseClass {...} 
class Foo : BaseClass {...} 
class Bar : BaseClass {...} 

// Two collections 
var fooDict = new Dictionary<long, Foo>; 
var barDict = new Dictionary<long, Bar>; 

// One method 
public void FooBar (Dictionary<long, BaseClass> dict) {...} 

// These do not work 
FooBar(fooDict); 
FooBar(barDict); 

있나요 : 여기

를 코드입니다 사전, 아니면 다른 패러다임을 사용해야합니까? 아니면 그냥 바보가되는 것입니까?

이에 대한 도움이나 조언을 주시면 감사하겠습니다.

미리 감사드립니다.

+0

그래서이 디자인으로 사용되지 않습니다 - 그것은 내가 미래의 독자 – Ruskin

+0

주 아래에 물결 모양의 대답을 살펴 보겠습니다 ... 그렇게 안전하지 않은 것 때문에 - WavyDavy 및 HimBromBreere에서 아래의 두 가지 좋은 해결책을 확인하십시오 - 모두 확인하십시오 – Ruskin

답변

4

트릭은 메소드를 일반화하고 where 키워드를 통해 유형을 제한하는 것입니다. 이 시도 :

namespace GenericsTest 
{ 
using System; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Program p = new Program(); 

     p.Run(); 

     Console.In.ReadLine(); 
    } 

    private void Run() 
    { 
     Dictionary<long, Foo> a = new Dictionary<long, Foo> { 
      { 1, new Foo { BaseData = "hello", Special1 = 1 } }, 
      { 2, new Foo { BaseData = "goodbye", Special1 = 2 } } }; 

     Test(a); 
    } 

    void Test<Y>(Dictionary<long, Y> data) where Y : BaseType 
    { 
     foreach (BaseType x in data.Values) 
     { 
      Console.Out.WriteLine(x.BaseData); 
     } 
    } 
} 

public class BaseType { public string BaseData { get; set; } } 

public class Foo : BaseType { public int Special1 { get; set; } } 

public class Bar : BaseType { public int Special1 { get; set; } } 
} 

출력 :

hello 
goodbye 
+0

이제 그게 영리합니다 ... 안전합니까? – Ruskin

+1

솔루션에서 동일한 이름을 제공하는 것이 더 좋았을 것입니다. 그러나 좋은 한 :) – HimBromBeere

2
public void FooBar<T> (Dictionary<long, T> dict) where T : BaseClass {...} 

편집 : 또 다른 방법은 FooBar가 동일한 인터페이스를 구현하도록하는 것입니다. 그런 다음 일반-물건없이 작업을 수행 할 수 있습니다

interface IFoo {} 
class Foo : IFoo {} 
class Bar : Bar {} 

public void FooBar(Dictionary<long, IFoo> dict) {...} 
+0

좋은,하지만 먼저 물결이있어;) – Ruskin

+0

Tidier. 훨씬 더 읽기 쉽습니다. – wavydavy

관련 문제