【问题标题】:What's wrong here on casting from T?从 T 进行投射有什么问题?
【发布时间】:2018-03-15 13:20:47
【问题描述】:

这是我的code

public class Program
{
    public static void Main(string[] args)
    {
        Factory factory = new Factory();
    }           
}     

public class Factory
{
    public Factory() {
        Animal animal = new Animal();
        MVCSender<Animal>(animal);                  
    }    

    public void MVCSender<T>(object elem) {
        WebAPIReceiver<T>(elem);
    }   

    public void WebAPIReceiver<T>(object elem) {
        WebAPIProcesser((T)elem);
    }

    public void WebAPIProcesser(Animal elem) {
        elem.Speak();
    } 
}  

public class Animal
{
    public Animal() {}

    public void Speak()
    {
        Console.WriteLine("Animal Speak!");
    } 
}  

我跨函数传递T,在“端点”上,我尝试使用已跨函数传递的T 类型转换通用object 类型。

这是一个自学问题,整体没有任何意义。

  1. 为什么我不能从TWebAPIProcesser((T)elem) 转换为Animal
  2. 在 C# 中写泛型(在函数名之后)是什么意思?它是否只是在任何函数声明之前替换template &lt;class T&gt;(例如C++)?

【问题讨论】:

  • 因为object 不是T 并且T 不是Animal。研究你得到的编译器错误。
  • 当您已经知道 T 是为了调用参数时,为什么还要使用参数对象?他们可以是 T elem
  • 2. public void WebAPIReceiver&lt;T&gt;(T elem) where T : Animal { WebAPIProcesser(elem); } 是传递 T 作为参数的方式。
  • @User.Anonymous 仍然不起作用rextester.com/QAUW36864
  • 当您将方法 WebAPIReceiver&lt;T&gt;WebAPIReceiver&lt;T&gt; 设为通用时,您想要实现什么?哪些类型可以替代T?为什么签名M(Animal elem) 不足以满足您的目的?

标签: c# generics casting


【解决方案1】:
public void WebAPIReceiver<T>(object elem) {
    WebAPIProcesser((T)elem);
}

与 C++ 模板相反,只有在您实际使用它们 是非法的情况下才会失败,C# 确保 any 调用您可以 make 必须是合法的。

在你的情况下:虽然T 在你的情况Animal,编译器必须确保你的方法适用于任何 T。但事实并非如此。对于任何非Animal,它都会失败。所以编译器会给你一个错误。

【讨论】:

    【解决方案2】:

    如果您回复我的答案是向我展示如何转换 从模板 T 到字符串(即推断 Animal 到字符串“Animal”)你 会得到我“接受”的答案!

    void Main()
    {
        Foo<Animal> foo = new Foo<Animal>();
        Animal animal = new Animal();
        Console.Write(foo.Get(animal));
    }
    
    public class Animal
    {
    }
    
    public class Foo<T> {
    
        public string Get(T entity)
        {
            return entity.GetType().Name;
        }
    }
    

    【讨论】:

    • 是的,但问题出在另一边。 string type = entity.GetType().Name; 当然很容易解决。但是当我到达 ApiController 时,您将如何从字符串构建对象并将其传递给类型化方法?我的意思是这很容易object entity = Activator.CreateInstance(entityType);(使用Type entityType = Type.GetType("" + type);),但是如何将object传递给WebAPIChange(Registration registration)rextester.com/GLDWA23838
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2018-06-23
    • 2015-03-03
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多