2014-12-21 7 views
0

이것이 잘못 표현되었거나 이전에 질문을 받았지만 관련이없는 것으로 보이는 경우 미안합니다. 매우 피곤합니다.하위 클래스의 형질을 얻으십시오

좋아요, 그래서 내가하고자하는 일은 하위 클래스의 인스턴스를 참조해야하는 상황에 대한 서브 클래스에서 내 특성의 가치를 얻는 것이지만 어떤 특성에 대한 정보가없는 것입니다. 사용하고있다. 이것은 내가 코드에서 설명하기가 더 쉽기 때문에 여기에 내가하려고하는 것이있다.

public class TraitUser<T> 
{ 
    public void DoThingWithT(T thing) 
    { 
     thing.ToString(); 
    } 
} 

public class TraitInspector 
{ 
    public void DoThing() 
    { 
     // This is where I run into my issue, 
     // I need to be able to get the trait that 
     // an instance of the TraitUser class is using to continue. 
     TraitUser<> tUser = GetRandomTraitUser()/*Imagine this returns an instance of TraitUser with a random trait, this is where my issue comes in.*/; 
    } 
} 

편집 : 일부 부분의 수정이 이제 더 쉽게 이해할 수 있어야합니다.

+0

두 개의 다른 클래스를 썼습니다. 하위 클래스는 무엇입니까? – LPs

+0

제목을 편집했습니다. "[제목에"태그 "가 포함되어 있어야합니까?] (http://meta.stackexchange.com/questions/19190/)"합의가 "아니오, 그렇지 않아야한다"는 것을 참조하십시오. –

답변

0

제가 이해가된다면 TrairInspector의 TraitUser 인스턴스에서 제네릭 유형 T에 대한 정보를 얻어야합니다.

public interface IGetTraitInfo 
{ 
    Type GetTraitObjectType(); 
    object GetTraitObject(); 
} 

public class TraitUser<T> : IGetTraitInfo 
{ 
    private T _thing; 

    public void DoThingWithT(T thing) 
    { 
     _thing = thing; 
    } 

    public Type GetTraintObjectType() 
    { 
     return typeof(T); 
    } 

    public Type GetTraitObject() 
    { 
     return _thing; 
    } 
} 

public class TrairInspector 
{ 
    public void InspectTraitUser(IGetTraitInfo traitUser) 
    { 
     Type traitType = traitUser.GetTraintObjectType(); 
     object data = traitUser.GetTraitObject(); 
    } 
} 
0

나는 완전히 이해하지 못했지만 도움이 될 것입니다.

public interface ITrait 
{ 
    string DoSomething(); 
} 

public class Trait<T> where T : ITrait, new() 
{ 
    public string DoSomething() 
    { 
     ITrait trait = new T(); 
     return trait.DoSomething(); 
    } 
} 

public class TraitUser : ITrait 
{ 
    public string DoThing() 
    { 
     return "return something"; 
    } 
} 

public class TrairInspector 
{ 
    public void DoThing() 
    { 
     Trait<TraitUser> traitUser = new Trait<TraitUser>(); 
     traitUser.DoSomething(); 
    } 
} 
관련 문제