C#中:声明和使用泛型类的列表,包括不同类型的,怎么样?不同类型、声明、列表、泛型类

2023-09-02 21:50:29 作者:好的人总是让人心心念念,好的总是不愿换掉,今天小编来分享20

有可能包含有以下通用类的任何 字符串,整数,浮点,长 作为类型:

Having the following generic class that would contain either string, int, float, long as the type:

public class MyData<T>
{
    private T _data;

    public MyData (T value)
    {
        _data = value;
    }

    public T Data { get { return _data; } }
}

我想获得的名单 迈德特&LT; T&GT; ,其中每个项目将是不同的 T

I am trying to get a list of MyData<T> where each item would be of different T.

我希望能够从名单中访问某个项目,并得到其数值如下所示code:

I want to be able to access an item from the list and get its value as in the following code:

MyData<> myData = _myList[0];    // Could be <string>, <int>, ...
SomeMethod (myData.Data);

其中 的someMethod() 声明如下:

where SomeMethod() is declared as follows:

public void SomeMethod (string value);
public void SomeMethod (int value);
public void SomeMethod (float value);

更新:

的someMethod() 是从另一层类的,我没有控制和 的someMethod(对象) 不存在。

SomeMethod() is from another tier class I do not have control of and SomeMethod(object) does not exist.

不过,我似乎无法找到一种方法,使编译器高兴。

However, I can't seem to find a way to make the compiler happy.

有什么建议?

感谢你。

推荐答案

代表可以真正帮助简化此,仍然保持事物类型安全的:

Delegates can really help simplify this, and still keep things type-safe:

    public void TestMethod1()
    {
        Action<SomeClass, int> intInvoke = (o, data) => o.SomeMethod(data);
        Action<SomeClass, string> stringInvoke = (o, data) => o.SomeMethod(data);

        var list = new List<MyData> 
        {
            new MyData<int> { Data = 10, OnTypedInvoke = intInvoke },
            new MyData<string> { Data = "abc", OnTypedInvoke = stringInvoke }
        };

        var someClass = new SomeClass();
        foreach (var item in list)
        {
            item.OnInvoke(someClass);
        }
    }

    public abstract class MyData
    {
        public Action<SomeClass> OnInvoke;
    }

    public class MyData<T> : MyData
    {
        public T Data { get; set; }
        public Action<SomeClass, T> OnTypedInvoke 
        { set { OnInvoke = (o) => { value(o, Data); }; } }
    }

    public class SomeClass
    {
        public void SomeMethod(string data)
        {
            Console.WriteLine("string: {0}", data);
        }

        public void SomeMethod(int data)
        {
            Console.WriteLine("int: {0}", data);
        }
    }