2014-03-12 60 views
0

我試圖創建一個類結構,這樣當繼承使用typeof

public abstract class Parent 
{ 
    //some class members here 
} 

public class Child : Parent 
{ 
    //some class members here 
} 

我覺得這裏有一個簡單的答案,但我對C#來說太新了,以找出我應該使用的搜索引擎。我嘗試過使用泛型,但我無法正確使用它。

我知道,如果沒有繼承我會寫

var Engine = new FileHelperEngine(typeof(Parent)); 

但是,這是我掙扎找出遺產的一部分。

對不起,我沒有提到FileHelperEngine引用FileHelpers C#庫

+3

也許這只是我,但真正的問題是什麼? – tweellt

+0

我的問題是,var Engine = new FileHelperEngine(typeof([我該如何抽象這塊?]))。我在typeof中放置什麼來使其變爲動態? – Ryan

+0

你可以調用'GetType()'。這應該返回當前對象的類型 – Default

回答

3

我認爲你正在尋找仿製藥,但我不能完全確定,因爲你的問題是不明確......

public abstract class ParentClass<T> where T : Parent 
{ 
    protected virtual void BuildQueries() 
    { 
     var Engine = new FileHelperEngine<T>(); 
     var r = Engine.ReadFile(ResumeName); 
    } 

    protected T TopType { get; set; } 

    // (...) 
} 

public class ChildClass : ParentClass<Child> 
{ 
    // don't need to override anything, because your property is generic now 
    // which means it will be of type `Child` for this class 
} 

public class FileHelperEngine<T> 
    where T : Parent // this generic constraint might not be necessary 
{ 
    public T[] ReadFile(string name) 
    { 
    } 
} 
+0

謝謝一堆。我之前曾使用過大部分這些屬性,但只是不知道如何將它們放在一起。我認爲這將是我需要的。在我回答之前,我會稍微測試一下。 – Ryan

+0

完美工作,正是我所期待的。謝謝 – Ryan