C#不能隐式地将类型T转换为类型T.

时间:2009-07-17 19:44:48

标签: .net-3.5 lambda extension-methods

我的方法:

public TableFilled<TKey, TRow> getTera()
    {

        Func<TablesFilled<TKey,TRow>> _getTera=new Func<TablesFilled<TKey,TRow>>(
        ()=>{return (TablesFilled<TKey,TRow>) chGetTera();});

       //Above does not compile says: Cannot convert type 
       //'AcapsVerify.FunctionalTables.TableFilled<TKey,TRow>' to 
       //'AcapsVerify.FunctionalTables.TablesFilled<TKey,TRow>'
       // the line below has the same blue underline error.
       return _getTera.TimeAndReport("Finished Teradata",OutputIfListener);

       // this works fine
       return chGetTera;
    }

它调用的静态方法

public static T TimeAndReport<T>(this Func<T> timedFunc, String reportLead, Action<String> reporterAction)
    {
        T result;
        var s = new System.Diagnostics.Stopwatch();
        s.Start();
        result = timedFunc();
        s.Stop();
        reporterAction(reportLead + " in " + s.WholePartOnly());
        return result;
    }

返回类定义:

public class TableFilled<TKey,TRow> where TRow: STeraRow<TKey>

5 个答案:

答案 0 :(得分:4)

您可以使用object进行类型转换。

return (T)(object)(result);

对我而言,它有效。

答案 1 :(得分:3)

那么TableFilled类型和TablesFilled类型之间有什么区别?要么返回类型中有拼写错误,要么两种类型之间没有隐式转换。

答案 2 :(得分:0)

我认为差异来自于过程中并非where TRow : STeraRow<TKey>指定的所有项目。

答案 3 :(得分:0)

问题是Func应该返回FilledTable而不是FilledTables

    abstract protected TableFilled<TKey, TRow> chGetTera();

    public TableFilled<TKey, TRow> getTera()
    {

        Func<TableFilled<TKey,TRow>> _getTera=new Func<TableFilled<TKey,TRow>>(
        ()=>{return  chGetTera();});

return _getTera.TimeAndReport("Finished Teradata",OutputIfListener);

 //return chGetTera();

    }

答案 4 :(得分:0)

Convert.ChangeType 应该是您问题的解决方案:

(T) Convert.ChangeType(yourObject, typeof(T));