使用不同的数据类型参数调用相同的方法而不重载 [英] Call same method using different datatype parameters without overloading

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

问题描述

我想在两个不同的场合调用一个方法。这两种情况通过两种不同类型的参数,它们因数据类型而异。如何实现这一点而不会超载。



这是我的代码



I want to call a method on two separate occasions. The two occasions pass two different types parameters, they differ by datatype. How do i achieve this without overloading.

This is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DifferentDatatypeOfMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intlist = new List<int>();
            intlist.Add(2);
            intlist.Add(3);
            intlist.Add(7);

            List<string> stringlist = new List<string>();
            stringlist.Add("A");
            stringlist.Add("B");
            stringlist.Add("C");

            Hit(intlist);
            Hit(stringlist);



            Console.Read();
        }

        public static void Hit(List<object> a) //doesn't work
        {
            Console.WriteLine(a[0]);
        }
    }
}

推荐答案

在这里阅读C#中的变量数据类型(它在那里自Visual Studio 2008 / C#3.0)...

http://msdn.microsoft.com/en-us/library/bb383973(v = vs.120).aspx [ ^ ]
Read here about variable data type in C# (it's there since Visual Studio 2008/C# 3.0)...
http://msdn.microsoft.com/en-us/library/bb383973(v=vs.120).aspx[^]


这是一个开始:

Here's a start:
public static void Hit(IList a)
{
    Console.WriteLine(a[0]);
}



您正在使用的两种类型的 List 实现了 IList 界面。

没有看到你在做什么我不能确定,但​​使用泛型 [ ^ ]看起来可能是一个很好的解决方案。


Both of the types of Lists you're using implement the IList interface.
Without seeing what else you are doing I can't be sure, but using generics[^] looks like it may be a good solution.


简单方法:
private void TestHit()
{
    var intlist = new List<int> {2, 3, 7};
    var stringlist = new List<string> {"A", "B", "C"};

    Hit(intlist);
    Hit(stringlist);
}

private void Hit<T1>(List<T1> theList)
{
    if (theList == null) throw new ArgumentNullException("theList");

    if (theList.Count == 0) throw new ArgumentOutOfRangeException("theList");

    Console.WriteLine(theList[0]);

}

方法'命令通过将占位符名称T1放在方法名称后的尖括号中来声明它使用一个泛型参数。在参数列表中,定义了在调用方法时,T1将在运行时变为的通用List。使用T1是一种常见的约定,但您可以使用任何非保留名称;如果你想写:

The method 'Hit declares it uses one generic parameter by putting the place-holder name "T1" in angle-brackets after the method name. In the parameter list a generic List of whatever 'T1 will become at run-time, as the method is invoked, is defined. Using "T1" is a common convention, but you could use any non-reserved name for it; if you wanted to write:

private void Hit<TypeToBeDetermined>(List<TypeToBeDetermined> theList);

这样就好了,但确实......详细。

That would be just fine, but ... verbose, indeed.


这篇关于使用不同的数据类型参数调用相同的方法而不重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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