C#中Object类型的隐含属性 - 是否可能?

时间:2017-05-18 22:55:43

标签: c# vb.net generics

我试图将以下函数从VB转换为C#:

Private Function CheckHeader(ByVal Request As Object, ByRef Response As Object) As Boolean
  CheckHeader = True
  If Request.Header Is Nothing Then
     CheckHeader = False
     Throw New System.ArgumentException("Header Object not found")
  End If
End Function

以下是我目前在C#中所拥有的内容:

private bool CheckHeader(object Request, ref object Response)
  {
     bool functionReturnValue = false;
     functionReturnValue = true;

     var localRequest = Request;

     if (localRequest.Header == null)
     {
        functionReturnValue = false;
        throw new System.ArgumentException("Header Object not found");
     }
     return functionReturnValue;
  }

问题在于Object类型的Request参数。在VB中,我们有隐含属性的很好的特性,当然C#并不喜欢一点。任何确实作为" Request"传递的对象。参数应该具有Header参数。我只是检查它是否在那里。我认为仿制药的使用可能适用于此,但我不确定要采取的路线。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

我认为你在c#中做同样事情的唯一方法就是使用dynamic关键字

它应该像vb.net的严格关闭

    private bool CheckHeader(dynamic Request, ref object Response)
    {
        bool functionReturnValue = false;
        functionReturnValue = true; //you should put true above instead

        var localRequest = Request; //not sure why this but whatever

        if (localRequest.Header == null)
        {
            functionReturnValue = false; //no need for this here, because of the throw
            throw new System.ArgumentException("Header Object not found");
        }
        return functionReturnValue; //at this point remove 
                                    //this variable and simply return true
    }

所以这应该没问题

    private bool CheckHeader(dynamic Request, ref object Response)
    {
        //Response variable should stay there since it might be a
        //breaking change, you should check if you can remove it

        if (Request.Header == null)
        {
            throw new System.ArgumentException("Header Object not found");
        }
        return true;
    }

答案 1 :(得分:0)

由于object没有Header属性,如果可能,我会将Request Object转换为c# interface。所以我会将代码更改为:

首先IRequest interface

public interface IRequest
{
    //Assuming Header is an object.
    MyHeaderObject Header {get;set;}
}

现在CheckHeader功能:

private bool CheckHeader(IRequest Request, ref object Response)
{
    bool functionReturnValue = false;
    functionReturnValue = true;

    var localRequest = Request;

    if (localRequest.Header == null)
    {
       functionReturnValue = false;
       throw new System.ArgumentException("Header Object not found");
    }
    return functionReturnValue;
}

现在,通过RequestCheckHeader的所有内容都需要实现IRequest

以下是一个例子:

public MyRequest : IRequest 
{
   public MyHeaderObject Header {get;set;}
}