无法获得泛型类型T C的值# [英] Not able to get value of generic type T C#

查看:83
本文介绍了无法获得泛型类型T C的值#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法获得通用类型的价值T



Not able to get value of generic type T

public class TableManagerOf<T> where T : IComparable
   {
       void test()
       {
           var obj = typeof(T);
           m_Properties = typeof(T).GetProperties();
           foreach (var item in m_Properties)
           {
               var value = item.GetValue(obj);
           }
       }
   }





我尝试过:



我一直在努力了解泛型类型在c#



What I have tried:

I have been trying a lot to understand how generic type works in c#

推荐答案

IComparable [ ^ ]没有属性。它只有一种方法。



对于你的另一个问题,与其堂兄模板相比,泛型非常简单。基本上创建了一个类,它可以接受符合约束条件的任何类。在您的情况下,任何实现 IComparable 的类都可以用于 T 。您可能想要的更多内容以及泛型(C#编程指南) [ ^ ]。



另一个密切相关的主题是协方差和逆变 [ ^ ]。
IComparable[^] has no properties. It has a single method.

To your other question, generics are pretty simple compared to their cousin templates. Basically a class is created which can accept any class conforming to your constraints. In your case, any class which implements IComparable can be used for T. All you could ever want and more is available in Generics (C# Programming Guide)[^] on MSDN.

Another closely related topic is Covariance and Contravariance[^].


T是一个Type,在你的情况下,T应该是一个实现IComparable的已定义的类或结构。但重要的是要记住,T只是在编写代码时定义需求,这意味着它是关于一个类而不是一个对象实例。

对GetProperties()的调用工作正常但你没有实例。那么无论T会有什么属性,你会从哪个对象中得到这些值?你需要一个实例。在你的代码中你将typeof(T)分配给obj,但是typeof(T)为你提供了Type而不是T的实例。下一行的GetProperties是Type的方法而不是T.的方法。如果你想要你的测试代码使用T实例工作尝试以下内容:

T is a Type and in your case T should be a defined class or struct that implements IComparable. But it is important to remember that T is just defining the requirement at time of writing your code, meaning it is about a class and not about an object instance.
The call to GetProperties() works fine but you do not have an instance. So whatever properties T would have, from which object would you expect the values? You need an instance for that. In your code you assign typeof(T) to obj, but typeof(T) gives you the Type and not an instance of T. The GetProperties on the next line is a method of Type and not of T. If you want your test code working using an instance of T try the following:
public class TableManagerOf<T> where T : IComparable, new()
    {
        void test()
        {
            var obj = new T();
            m_Properties = typeof(T).GetProperties();
            foreach (var item in m_Properties)
            {
                var value = item.GetValue(obj);
            }
        }
    }





额外的新()是为了确保T是一个使用默认构造函数的类,因此可以使用无参数构造函数new T()创建新实例。



祝你好运!



The additional new() is to make sure T is a class with a default constructor, so a new instance can be created using a parameterless constructor new T() .

Good luck!


这篇关于无法获得泛型类型T C的值#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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