C# 无法从';输出T';至';输出组件';

C# 无法从';输出T';至';输出组件';,c#,C#,下面是一些未编译的C#代码,给出了以下信息: 无法从“输出T”转换为“输出组件” public void Get(out tc),其中T:Component { m_组件。TryGetValue(类型(T),输出c); } 下面是编译的代码: public void Get<T>(out T c) where T : Component { Component temp; m_components.TryGetValue(typeof

下面是一些未编译的C#代码,给出了以下信息:

无法从“输出T”转换为“输出组件”

public void Get(out tc),其中T:Component
{
m_组件。TryGetValue(类型(T),输出c);
}
下面是编译的代码:

    public void Get<T>(out T c) where T : Component
    {
        Component temp;
        m_components.TryGetValue(typeof(T), out temp);
        c = (T)temp;
    }
public void Get(out tc),其中T:Component
{
组件温度;
m_元件TryGetValue(类型(T),输出温度);
c=(T)温度;
}
我想知道为什么第一个代码无效,因为“where T:Component”明确指出T是Component类型


谢谢

我认为问题出在外,与泛型无关

我们可以产生如下相同的错误

class A
{
}

void fn(out object x)
{
 x= new object();
}
void main()
{
 A x;
fn(out x); //error
}
这很有趣

我没有答案,但值得注意的是(无论如何,对我来说),以下方法是有效的:

    public void M<T> (out T c) where T : Test
    {
        // Test m;
        // A(out m);
        // c = (T) m;

        A(out c);
    }

    public void A<T> (out T t) where T : Test
    {
        t = null;
    }
public void M(out tc),其中T:Test
{
//测试m;
//A(m);
//c=(T)m;
A(c);
}
公共无效A(out T T),其中T:Test
{
t=零;
}
--编辑:


(这很有趣,因为即使它是
out-object t
,它仍然不能在
out-t
out-object
之间转换)

这是因为
out
参数类型不能转换变量类型必须与参数类型完全匹配。

见:


好吧,我想起来了:

如果您有以下情况怎么办:

 public class BaseClass { ... }
 public class SubClass : BaseClass { ... }
然后我有了密码:

 Dictionary<int, BaseClass> comps;

 public void Get<T>(int num, out T c) where T : BaseClass
 {
     comps.TryGetValue(num, out c);
 }
字典comps;
公共void Get(int num,out tc),其中T:BaseClass
{
补偿TryGetValue(数值,输出c);
}
我试着这样称呼它:

 SubClass sub;
 Get<SubClass>(1, out sub);
子类sub;
Get(1,out sub);

Sub假设键为1的
基类
实际上是
基类
,而不是
子类
。或者可能是
OtherSubClass
其中
OtherSubClass:BaseClass

我将尝试一下@Rex答案的更详细版本,以及@Courtney签名的稍微更正版本,因为类型是组件,而不是对象。考特尼的回答基本上是对的,只是类型有点不对劲

bool TryGetValue(Type key, out Component result)
{
       if (this.Contains(key))
       {
           result = this[key]; // the type of result is Component!
           return true;
       }

      return false;
}
通过将T作为对象类型传递,您试图将基类型组件隐式转换为子类型T。这就是第二个示例工作的原因。TryGetValue不知道泛型类型t,它认为m_组件中的所有内容都是组件对象


这是一件很常见的事情,让人陷入思考倒退。因为它是一个参数,而不是返回类型,所以您会误以为它应该像其他任何参数一样工作。然而,由于它是一个输出,因此实际上最好将其视为用于此目的的返回类型。。。它将尝试将其内部功的值分配给您提供的参数。

如果T被定义为Component类型,为什么需要将“Get”作为泛型方法?也许你是天堂;t在这里提到了确切的情况。在等待Skeet先生就这个有趣的问题向我们提供启发时,他转动着大拇指。这是一个重复@Amby:m_components是一个组件字典。它可能包含基于抽象类组件的任何派生对象。用法例如:PhysicComponent PhysicComponent;模型组件模型组件;实体.Get(out physicComponent);获取(输出模型组件);
 SubClass sub;
 Get<SubClass>(1, out sub);
bool TryGetValue(Type key, out Component result)
{
       if (this.Contains(key))
       {
           result = this[key]; // the type of result is Component!
           return true;
       }

      return false;
}