C#泛型 - 如何返回一个特定的类型? [英] C# Generics - How do I return a specific type?

查看:321
本文介绍了C#泛型 - 如何返回一个特定的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我会对此完全错误的。

Maybe I'm going about this all wrong.

我有一堆类,从模型类派生,一个基类和一帮常见的属性和方法。我希望它们都实现一组功能:

I have a bunch of classes that derive from the "Model" class, a base class with a bunch of common properties and methods. I want them all to implement a set of functionality:

public abstract void Create();
public abstract T Read<T>(Guid ID);  //<--Focus on this one
public abstract void Update();
public abstract void Delete();



然后,我实现它的子类,如约会,像这样:

Then I implement it in a child class like "Appointment" like so:

public override T Read<T>(Guid ID)
{
  var appt = db.Appointments.First(a => a.AppointmentID.Equals(ID));
  var appointment = new Appointment()
  {
    DateEnd = appt.dateEnd.GetValueOrDefault(),
    Location = appt.location,
    Summary = appt.summary
  };
return appointment;
}

这抛出一个异常无法隐式转换类型'约会'给T 。如果我改变了方法,对公众覆盖预约读(GUID ID)的签名,那么编译器说,我还没有实现在子类中的抽象方法。

This throws an exception "Can't implicitly convert type 'Appointment' to T". If I change the method's signature to "public override Appointment Read(Guid ID)", then the compiler says that I've not implemented the abstract method in the child class.

我在想什么?任何人都可以给我一些示例代码?

What am I missing? Can anyone give me some code samples?

推荐答案

看起来你可以使用一个通用的基类!考虑类似如下:

It looks like you could use a generic base class! Consider something like the following:

class Model<T>
{
    public abstract T Read(Guid ID);
}

class Appointment : Model<Appointment>
{
    public override Appointment Read(Guid ID) { }
}

现在你的子类都强类型。当然,代价是你不再有单一的基类。 A 模型<任命> 是不一样的东西作为一个模型<客户> 。我还没有普遍发现这是一个问题,但是,因为functionality--接口都差不多有一点共同的,但他们都用不同类型的工作。

Now your subclasses are all strongly typed. Of course, the tradeoff is that you no longer have a single base class. A Model<Appointment> isn't the same thing as a Model<Customer>. I have not generally found this to be a problem, though, because there's little common functionality-- the interfaces are similar, but they all work with different types.

如果你想要一个共同的基础,你当然可以欺骗和实施对象基于接口,并且相同的一般任务。例如,事中的精神(未经测试,但这个想法的存在):

If you'd like a common base, you can certainly cheat and implement an object-based interface that does the same general tasks. E.g., something in the spirit of (untested, but the idea's there):

interface IModelEntity
{
    object Read(Guid ID);
}

class Model<T> : IModelEntity
{
    public T Read(Guid ID)
    {
        return this.OnRead(ID); // Call the abstract read implementation
    }

    object IModelEntity.Read(Guid ID)
    {
        return this.OnRead(ID); // Call the abstract read implementation
    }

    protected abstract virtual T OnRead(Guid ID);
}

class Appointment : Model<Appointment>
{
    protected override Appointment OnRead(Guid ID) { /* Do Read Stuff */ }
}

这篇关于C#泛型 - 如何返回一个特定的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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