将返回类型转换为数组C#

时间:2015-01-14 23:06:46

标签: c# arrays

我有一个ts返回Array的方法。我遇到一个无法将返回类型转换为数组的类的问题。

这是我的方法:

      public Model.BaseType[] returnPayment_Gateway()
    {
        IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
        WebHeaderCollection headers = request.Headers;
        var settings = new DataContractJsonSerializerSettings { EmitTypeInformation = EmitTypeInformation.Never };

        MemoryStream stream1 = new MemoryStream();

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.BaseType),settings);

        Model.Payment_Gateway[] allRecords = null;


        if (headers["ServiceAuthentication"] != null)
        {
         string   ServiceAuthentication = headers["ServiceAuthentication"].ToString();
          bool  serviceAuth = Service_Authentication(ServiceAuthentication);

          DAL.DataManager dal = new DAL.DataManager();

            if (serviceAuth == true)
            {
               allRecords = dal.Get_Payment_Gateway();

            }
        }

        else
        {


               // Create a new customer to return


            return new Model.ReturnResponse() { StatusCode = 201, StatusDescription = "Authentication Fails" };


        }

        return allRecords;
    }

我的问题是在其他部分,不知道如何将Model.ReturnResponse()转换为数组现在我收到此错误:

无法将类型ReturnResponse隐式转换为Model.BaseType []

如果你想看我的3个班级:

这是基类:

[Serializable]
[DataContract]
[KnownType(typeof(Payment_Gateway))]
[KnownType(typeof(ReturnResponse))]

public class BaseType 
{

}

这是Payment_Gateway类:

[DataContract]
public class Payment_Gateway:BaseType
{
    [DataMember]
    public int Payment_Gateway_ID { get; set; }

    [DataMember]
    public string Payment_Gateway_Name { get; set; }

    [DataMember]
    public string Payment_Gateway_URL { get; set; }

    [DataMember]
    public string Payment_Gateway_Description { get; set; }

这是ReturnResponse类:

[DataContract]
public class ReturnResponse:BaseType
{
    [DataMember]
    public int StatusCode { get; set; }

    [DataMember]
    public string StatusDescription { get; set; }


}

2 个答案:

答案 0 :(得分:3)

而不是尝试返回单个ReturnResponse

return new Model.ReturnResponse()
    { StatusCode = 201, StatusDescription = "Authentication Fails" };

返回一个数组,其中包含单个元素,因为这是您希望返回的方法:

return new[] {
    new Model.ReturnResponse()
        { StatusCode = 201, StatusDescription = "Authentication Fails" }
    }

答案 1 :(得分:0)

如果您将返回数据封装在指示响应类型(成功或失败)的响应对象以及结果数据中,而不是您在此处设计的层次结构,则会更容易。

该类可能如下所示

public enum ResponseTypes
{
    Success,
    Failure
}

public class Response
{
    public ResponseTypes ResponseType {get; set;}
    public Exception Error {get;set;}
    public BaseType[] Data {get;set;}
}

这样它就像一个信封到你的实际数据,并为调用者提供状态,以便在读取数据(结果)之前知道调用是否成功,也许是出于什么原因

它与WCF在幕后(至少在SOAP中)的行为方式相同,它围绕您的数据合同与消息信封/附件,为调用者添加更多元数据以解释呼叫状态。