C#方法通用返回类型转换 [英] C# method generic return type casting

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

问题描述

我试图在具有泛型返回类型的接口中创建一个方法,但是我无法将泛型转换为特定的类型/类。但是,如果我将泛型而不是方法放在接口上,我就可以进行强制转换。

I am trying to create a method in an interface with a generic return type but I fail to cast the generic to a specific type/class. But if I put the generic on the interface instead of the method I am able to do the casting.

换句话说,为什么这样做有效

In other words, why does this work

public class Rain {
    public string propA {get;set;}
}
public interface IFoo<T> {
    T foo();
}

public class Bar : IFoo<Rain> {
    Rain foo() { 
        //...
        return new Rain();
    }
}

public bar = new Bar();
Rain rain = bar.foo();

但这不可能吗?

public class Rain {
    public string propA {get;set;}
}
public interface IFoo {
    T foo<T>();
}

public class Bar : IFoo {
    T foo<T>() { 
        //...
        return new Rain();
    }
}

public bar = new Bar();
Rain rain = bar.foo<Rain>();

还有其他方法(不使用 Convert.ChangeType())?

Is there any other way around ( without using Convert.ChangeType())?

推荐答案

区别是:

// On this line you specify that the interface's generic type paramter 'T' is of type 'Rain',
// so the method implements the interface and returns a 'Rain'
public class Bar : IFoo<Rain> {
    Rain foo() { // <= implements IFoo<Rain>.foo, where T = Rain so foo returns 'Rain'
        return new Rain();

// In this version, the generic type parameter is declared on the method. It could be any type when the method is called, yet you always return a 'Rain'
public class Bar : IFoo {
    T foo<T>() { // <= implements IFoo.foo<T> but the type of T is not specified yet
        return new Rain();

解决方案取决于您的意图。

The "solution" for this depends on what your intentions are.


  • 您为什么想要界面上的通用参数?

  • 此外,如果总是返回 Rain ,为什么还要在 foo 方法上使用通用参数? ?

  • Why would you not want the generic parameter on the interface?
  • Also, why would you want a generic parameter on the foo method, if you always return Rain anyways?

当然,无论如何,您都可以像这样进行投射:

Of course, in any case, you could just cast it like this:

T Foo<T>()
{
    object result;
    result = new Rain();
    return (T)result; // note, this will throw at runtime if 'result' cannot be cast to 'T'
}

// call like this:
Bar.Foo<Rain>();

但是我认为您的第一种方法 IFoo< T> 非常合理,所以为什么不使用它呢?

But I think your first approach IFoo<T> makes perfect sense so why not use it?

更新

基于根据您的评论:您还可以定义多个通用参数:

Based on your comment: You can also define multiple generic parameters:

public interface IFoo<T1, T2>
{
    T1 foo();
    T2 foo2();
}

// implementation:
public class Bar : IFoo<Rain, Other>
{
    Rain foo() { /* ... */ }
    Other foo2() { /* ... */ }
}

这篇关于C#方法通用返回类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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