通用对象创建总是返回空值

时间:2011-02-08 19:46:40

标签: c# generics

编辑我更新了问题的完整性。

我有来自iPHone客户端的传入REST调用。它旨在使用特定于类型的对象 响应通用请求。例如:

http://localhost:81/dashboard/group/id/0

从Regions类型

返回数据

http://localhost:81/dashboard/group/id/1

从Customers类型

返回数据

http://localhost:81/dashboard/group/id/2

从用户类型

返回数据

等等。

WCF Dashboard.svc服务公开了一个基本方法GetGroupById 我用它来确定并返回特定类型的响应:

public class Dashboard:GroupBase,Contracts.IDashboardService     {         private string name = String.Empty;

    public Dashboard() : base()
    {

        if (!ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated)
            throw new WebException("Unauthorized: Class: Dashboard, Method: Dashboard()",
                System.Net.HttpStatusCode.Forbidden);

        name = ServiceSecurityContext.Current.PrimaryIdentity.Name;

    }

    public override System.IO.Stream GetGroupById(string id)
    {
        return base.GetGroupById(id);
    }

}

现在,在我的抽象基类中,GetGroupById有一个填充的switch / case语句 并根据相应的groupid参数返回唯一的数据传输对象:

            public abstract class GroupBase
{

    protected GroupBase () { }

    public virtual Stream GetGroupById(string id)
    {
         // I have tried assigning response to null or, in this case,
         // assigning it to a random service object. I have also tried
         // IObjectFactory response; The last fails at compile-time and
         // the other two always produce null  
         IObjectFactory response = 
            ObjectFactory<IObjectFactory, UserService>.Create();  

        var groupId = System.Convert.ToInt32(id);
        var serializer = new JavaScriptSerializer();

        byte[] bytes = null;

        var message = String.Empty;

        try
        {

            switch (groupId)
            {
                case 0: // regions

                    response = ObjectFactory<IObjectFactory, RegionService>.Create();
                    break;

                case 1: // customers

                    response = ObjectFactory<IObjectFactory, CustomerService>.Create();
                    break;

                case 2: // users
                    response = ObjectFactory<IObjectFactory, UserService>.Create();
                    break;
            }

        }

        catch (EngageException oops)
        {
            message = oops.Message;
        }



        bytes = Encoding.UTF8.GetBytes(serializer.Serialize(response));

        return new MemoryStream(bytes);

    }

}

客户ObjectFactory类用于创建特定于类型的对象:

public static class ObjectFactory其中T:F,new()     {         public static F Create()         {             返回新的T();         }     }

我遇到问题的地方我的ObjectFactory引擎盖下发生了什么。我总是 得到** null **回来。例如,请考虑以下REST HTTP GET:

http://localhost:81/dashboard/group/id/2

上面的命令要求数据库中所有用户的JSON字符串。因此, UserService类传递给ObjectFactory方法。

  public class UserService : IObjectFactory
{
    DomainObjectsDto IObjectFactory.Children
    {
        get
        {

            return new Contracts.DomainObjectsDto(UserRepository
                                .GetAllUsers().Select
                                (p => new Contracts.DomainObjectDto
                                 {
                                     Title = GroupTypes.Customer.ToString(),
                                     Id = p.CustomerId.ToString(),
                                     Type = p.GetType().ToString()
                                 }));
        }

    }

    string IObjectFactory.Method
    {
        get;
        set;
    }

    string IObjectFactory.Status
    {
        get;
        set;
    }

    etc...

并且,只读Get属性从UserRepository获取数据,填充数据传输对象 (如下图所示)

[DataContract]
public class DomainObjectDto
{
    [DataMember]
    public string Title { get; set; }
    [DataMember]
    public string Id { get; set; }
    [DataMember]
    public string Type { get; set; }
}

   [CollectionDataContract]
    public class DomainObjectsDto : List<DomainObjectDto>
    {
        public DomainObjectsDto() { }
        public DomainObjectsDto(IEnumerable<DomainObjectDto> source) : base(source) { }
    }

并且应该将用户数据的序列化JSON字符串返回给客户端。但是,我的对象工厂类中的泛型类型T始终为null:

 public static F Create()
    {
        return new T(); // <-- always null!
    }

任何想法??

3 个答案:

答案 0 :(得分:2)

很难说没有在上下文中看到你的工厂的调用,但我的直觉是groupId不在交换机范围内,因此你得到了你默认的null。我会添加一个默认情况并抛出一个超出范围的异常,看看这是不是你的问题。

答案 1 :(得分:0)

最好在switch语句中添加默认情况,例如:

default: 
  throw new Exception( "groupId " + groupId + " not found" );

答案 2 :(得分:0)

更改第IObjectFactory response = null;行以删除默认设置,即IObjectFactory response;。现在编译器会告诉你是否有一个分支没有分配它(当然,它不能告诉你是否以某种方式分配给null)。另请注意,至少有两种方法可以从null(等)中获取new,但these是边缘情况 - 我怀疑它们是否有所贡献(仅提及完整性)。< / p>