C#返回正确的对象类型

rov*_*red 3 c# generics return object emgucv

    public Object get()
    {
        switch (current_image_type)
        {
            case(image_type.Gray):
                return (Image<Gray, Byte>)image_object;
            case(image_type.Bgr):
                return (Image<Bgr, Byte>)image_object;
            default:
                throw new Exception("No Image type set for ImageCV");
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以在这个get函数中我不知道在运行时返回什么对象类型,所以我只返回了Object超类.但是,这并不好,因为当我得到返回的Object超类时,我将无法访问Image<,>子类函数,除非我知道要将其转换为什么.有没有办法让我检查current_image_type在运行时返回所需对象类型的对象类型?谢谢.

McG*_*gle 6

由于current_image_type是包含类的可变属性,因此您无法在编译时知道返回类型是什么.

我会Image<T1, T2>实现一个类似的接口IImage,它封装了调用者需要的所有方法/属性.然后你可以返回一个打字的对象:

public IImage get() { ... }
Run Code Online (Sandbox Code Playgroud)

如果您无法修改Image<T1, T2>,您可以创建一种可以完成相同操作的中介类:

public ImageMediator<T> : IImage
{
    private readonly Image<T, Byte> _image;

    public ImageMediator(Image<T, Byte> image)
    {
        _image = image;
    }

    // TODO implement IImage
}
Run Code Online (Sandbox Code Playgroud)

然后你可以IImage通过简单地传入image_object调解器来获得一个类型:

case(image_type.Gray):
    return new ImageMediator<Gray>((Image<Gray, Byte>)image_object);
case(image_type.Bgr):
    return new ImageMediator<Bgr>((Image<Bgr, Byte>)image_object);
Run Code Online (Sandbox Code Playgroud)