C#返回正确的对象类型

时间:2013-10-18 05:24:08

标签: c# generics object return 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");
        }
    }

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

3 个答案:

答案 0 :(得分:6)

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

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

public IImage get() { ... }

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

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

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

    // TODO implement IImage
}

然后,只需将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);

答案 1 :(得分:0)

 // Example of checking for type Image<int,string>
        if(current_image_type.GetType() == typeof(Image<Int32,string))
            return (Image<Int32,string>)current_image_type;

答案 2 :(得分:0)

几种不同的方式。您可以使用GetType()函数或使用“as”运算符,当且仅当它是该类型时,它才会将对象强制转换为给定类型。

我没有编译这个,所以不确定确切的语法,但你明白了......

// one way
Type t = o.get().GetType();
if ( t == typeof( Image<Gray, Byte> ) {
// we have an Image<Gray, Byte>
}

// another way
Image<Gray, Byte> grb = o.get() as Image<Gray, Byte>;
if ( grb != null ) {
// we have an Image<Gray,Byte>
}
相关问题