2011-09-08 93 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

相关问题