从泛型方法调用重载的泛型方法 [英] Call overloaded generic method from generic method

查看:50
本文介绍了从泛型方法调用重载的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:为什么从未调用 AddData(string data)?当我调用 ds.Add("Some text")时, data 参数的类型在编译时是已知的,因此 Add 的重载实现应该调用 AddData(string)方法(或者这就是我所希望的)

My question is: Why is AddData(string data) never called? When I call ds.Add("Some text") then the type of data parameter is known at compilation time thus the overloaded implementation of Add should call AddData(string) method (or this is what I was hoped for)

输出为

Ignore data of type System.String
Ignore data of type System.Double

using System;

namespace GenericCall
{
    interface IDataStore
    {
        void Add<T>(T data);
    }

    class MyDataStore : IDataStore
    {
        public void Add<T>(T data)
        {
            AddData(data);
        }

        private void AddData<T>(T data)
        {
            Console.WriteLine($"Ignore data of type {data.GetType()}");
        }

        private void AddData(string data)
        {
            Console.WriteLine("Accept string data");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyDataStore ds = new MyDataStore();
            ds.Add("Some text");
            ds.Add(3.14);
        }
    }
}

推荐答案

在代码编译时会发生重载解析.

Overload resolution happens at compile time for your code.

在编译时,编译器不知道 T 的实际含义,因此此调用:

At compile time, the compiler has no knowledge of what T actually is, so this call:

public void Add<T>(T data)
{
    AddData(data); <------
}

根据一种在运行时解决过载的方法是使公共 Add 接受一个 dynamic 参数:

One way to make overload resolution happen at runtime is to make the public Add accept a dynamic parameter:

// you should change the interface declaration also!
public void Add(dynamic data)
{
    AddData(data);
}

这将产生输出:

Accept string data
Ignore data of type System.Double

这篇关于从泛型方法调用重载的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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