将方法转换为通用方法? [英] Converting Method to Generic Method?

查看:84
本文介绍了将方法转换为通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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;
}

}
返回pBo;



$ b我需要转换这个方法,对象类型(现在我只接受类型为BOEod的对象)。

因为我对.Net是新手,所以不用如何使用泛型。

 <$ c $可以使用泛型来完成这项工作吗? 

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

这里主要的是我需要改变传递对象(PBO)的属性并返回它。 你需要 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) 
其中T:IIsValid {..}


I have created a Method shown below,

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;
}

I need to convert this method, in such a way that it should accept all Type of Objects(now i am accepting only Objects of type "BOEod").

As i am newbie to .Net so don no exactly how to use Generics. Can i accomplish this using Generics.?

Solution Something like this:

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

Here Main thing is i need to change the Property of the Passed Object(pBO) and return it.

解决方案

You would need BOEod to implement an interface which defines IsValid.

You would then add a generic constraint to your method to only accept objects implementing that interface.

  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{..}

这篇关于将方法转换为通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆