2011-09-08 99 views
1

我創建瞭如下圖所示的方法,將方法轉換爲通用方法?

public BOEod CheckCommandStatus(BOEod pBo, IList<string> pProperties) 
{ 
    pBo.isValid = false; 
    if (pProperties != null) 
    { 
     int Num=-1; 
     pBo.GetType().GetProperty(pProperties[0].ToString()).GetValue(pBo, null); 
     if (ifIntegerGetValue(pBo.GetType().GetProperty(pProperties[0].ToString()).GetValue(pBo, null).ToString(), out Num)) 
     { 
      if (Num == 1) 
       pBo.isValid = true; 
     } 

    } 
    return pBo; 
} 

我需要轉換這種方法,在這樣一種方式,它應該接受對象的所有類型(現在我只接受型「BOEod」的對象)。

因爲我是新手到.Net所以不準確如何使用泛型。我可以使用泛型完成此操作嗎?

解決事情是這樣的:

public T CheckCommandStatus<T>(T pBO, Ilist<string> pProperties){..} 

這裏主要的事情是我需要更改傳遞的對象(PBO)的財產和返回。

回答

5

您需要BOEod來實現一個接口,該接口定義了IsValid

然後,您會爲您的方法添加一個通用約束,只接受實現該接口的對象。

public interface IIsValid 
    { 
     bool IsValid{get;set;} 
    } 

....

public class BOEod : IIsValid 
    { 
     public bool IsValid{get;set;} 
    } 

....

public T CheckCommandStatus<T>(T pBO, IList<string> pProperties) 
where T : IIsValid{..} 
+0

感謝您的好回覆。我嘗試一下。讓你知道 – sandeep

1
public BOEod CheckCommandStatus<T>(T pBo, IList<string> pProperties) where T : IBOEod 
{ 
    pBo.isValid = false; 
    if (pProperties != null) 
    { 
     int Num=-1; 
     pBo.GetType().GetProperty(pProperties[0].ToString()).GetValue(pBo, null); 
     if (ifIntegerGetValue(pBo.GetType().GetProperty(pProperties[0].ToString()).GetValue(pBo, null).ToString(), out Num)) 
     { 
      if (Num == 1) 
       pBo.isValid = true; 
     } 

    } 
    return pBo; 
} 

public interface IBOEod 
{ 
    bool IsValid {get;set;} 
} 

所有類型,你想傳遞給這個方法必須實現IBOEod接口。

+0

它的工作!非常感謝 – sandeep

相關問題