从泛型方法返回某种类型

Sir*_*oma 0 .net c# generics mono

我对泛型方法有疑问.

假设我正在创建一个带有自定义UI的游戏,它有ResourceManager类.有方法从中获取对象ResourceManager并返回泛型类型,这里是类代码:

public class ResourceManager
{
        // The list that store the object
        private List<Control> _objects = new List<Control>();

        // Add object into the list
        public void Add(params Control[] objects)
        {
            _objects.AddRange(objects);
        }

        // Get the object from the list
        public T GetObject<T>(string name)
        {
            try
            {
                foreach (Control obj in _objects)
                {
                    if (obj.Name == name)
                        return (T)Convert.ChangeType(obj, typeof(T));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return default(T);
        }
}
Run Code Online (Sandbox Code Playgroud)

如你所见,Objects是Control类.在我的项目中,很少有类继承这个类,让我们说它Button,ImageCheckBox

我打电话时代码运行顺畅:

CheckBox checkBox = ResourceManager.GetObject<CheckBox>("CheckBox1");
Control control = ResourceManager.GetObject<Control>("Control1");
Run Code Online (Sandbox Code Playgroud)

问题是,它接受任何类型,如:

string str = ResourceManager.GetObject<string>("blablabla1");
int num = ResourceManager.GetObject<int>("blablabla2");
Run Code Online (Sandbox Code Playgroud)

我只是希望代码不会在类型不是Control和它的继承时编译.谢谢!

TGH*_*TGH 5

添加约束 public T GetObject<T>(string name) where T:Control