简体   繁体   English

函数C#的通用参数

[英]generic parameter to function c#

Good day! 美好的一天! Can't understand why do compiler highline it as error. 无法理解为什么编译器将其高行显示为错误。 Could somebody tell me "why". 有人可以告诉我“为什么”。 What do I wrong? 我怎么了 So, I have one generic class 所以,我有一个通用类

    public abstract class SimpleElement<TDataIndexer> where TDataIndexer:IDataIndexator 
{
    public TDataIndexr[] po_registr;
    protected Update updateDelegate;
}

Also, I have delegate, which dealing with updating visual component 另外,我有代表,负责更新视觉组件

public delegate object Update(IDataIndexator[] regs);

My delegate requires parameter type IDataIndexer . 我的委托需要参数类型IDataIndexer How I can pass generic parameter to that delegate? 如何将通用参数传递给该委托?

public delegate object Update(IDataIndexator[] regs);
public abstract class SimpleElement<TDataIndexer> where TDataIndexer:IDataIndexator 
    {
        public TDataIndexr[] po_registr;
        protected Update updateDelegate;
        public function foo(){
            this.updateDelegate(po_registr); // here is error that parameter should be IDataIndexator[], but not TDataIndexer[]
        }
    }

In order for what you think should happen automatically to work, your TDataIndexer must be constrained to a class 为了使您认为应该自动发生的事情,必须将TDataIndexer限制为一个class

public abstract class SimpleElement<TDataIndexer> 
    where TDataIndexer:class, IDataIndexator 
{ ...}

Live example: http://rextester.com/KDI86395 实时示例: http//rextester.com/KDI86395

Try use .Cast 尝试使用.Cast

public interface IDataIndexator { }

public delegate object Update(IDataIndexator[] regs);
public abstract class SimpleElement<TDataIndexer> where TDataIndexer : IDataIndexator
{
    public TDataIndexer[] po_registr;
    protected Update updateDelegate;
    public void foo()
    {
        this.updateDelegate(po_registr.Cast<IDataIndexator>().ToArray()); // here is error that parameter should be IDataIndexator[], but not TDataIndexer[]
    }
}

The fact that TDataIndexr : IDataIndexator doesn't mean that TDataIndexr[] is IDataIndexator[] in the eyes of the compiler. 在编译器看来, TDataIndexr : IDataIndexator并不意味着TDataIndexr[]IDataIndexator[]

Create IDataIndexator[] or do this.updateDelegate(po_registr.Cast<IDataIndexator>().ToArray()); 创建IDataIndexator[]或执行此操作this.updateDelegate(po_registr.Cast<IDataIndexator>().ToArray()); .

Basically in a way the system expects to get a parameter of type Array<IDataIndexator> , you are passing Array<SomeType> , where typeof(SomeType) != typeof(IDataIndexator) . 基本上,系统希望通过某种方式获得Array<IDataIndexator>类型的参数,您将传递Array<SomeType> ,其中typeof(SomeType) != typeof(IDataIndexator) Therefore for the compiler typeof(Array<IDataIndexator>) != typeof(Array<SomeType>) and error is produced. 因此,对于编译器typeof(Array<IDataIndexator>) != typeof(Array<SomeType>)会产生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM