将方法转换为通用方法?

san*_*eep 1 .net c# generics

我创建了一个如下所示的方法,

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;
}
Run Code Online (Sandbox Code Playgroud)

我需要转换这个方法,它应该接受所有类型的对象(现在我只接受类型为"BOEod"的对象).

因为我是.Net的新手,所以不知道如何使用泛型.我能用Generics完成这个吗?

解决方案像这样:

public T CheckCommandStatus<T>(T pBO, Ilist<string> pProperties){..}
Run Code Online (Sandbox Code Playgroud)

这里主要是我需要更改传递对象的属性(pBO)并返回它.

Dav*_*ale 5

您需要BOEod实现一个定义的接口IsValid.

然后,您将向方法添加通用约束,以仅接受实现该接口的对象.

  public interface IIsValid
  {
      bool IsValid{get;set;}
  }
Run Code Online (Sandbox Code Playgroud)

....

  public class BOEod : IIsValid
  {
      public bool IsValid{get;set;}
  }
Run Code Online (Sandbox Code Playgroud)

....

public T CheckCommandStatus<T>(T pBO, IList<string> pProperties) 
where T : IIsValid{..}
Run Code Online (Sandbox Code Playgroud)