new 一个对象时如何获得泛型?

本文探讨了在Java中如何通过getGenericSuperclass()方法获取父类的泛型参数,并提出了一个问题:是否可以在对象实例已存在的基础上获取其泛型信息。
一般通常用 ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
也就是 getGenericSuperclass() 方法去拿泛型 ,通过名字我们的得知,这个拿的是 父对象的泛型 super class generic
自然 理论上在 new时 是无法的得到泛型的。。。。
不过话又说出来 如果 这个实现方式是 基于回调的,那么通过回调 时这个实例已经存在了 可不可以拿 这个对象的泛型呢?

呵呵 还望还望指点下,个人觉得通过某种手段是可以拿到的,等我 斟酌出来时 再帖出来哈哈
做下广告
[url=http://www.sharpRen.com]欢迎访问 犀利人社区 sharpRen.com[/url]
[url=http://blog.sharpRen.com]欢迎访问 犀利人博客 blog.sharpRen.com[/url]
[url=http://java.sharpRen.com]欢迎访问 犀利人java论坛 java.sharpRen.com[/url]

[img]http://www.sharpren.com/images/wind/logo.png[/img]
在 C# 中,`List<T>` 是一个集合,用于存储多个相同类对象。若需要获取 `List<T>` 中每个对象的属性名称(即列名),可以通过反射(Reflection)来实现。反射允许在运行时动态获取类的信息,包括其属性、方法、字段等。 以下是一个完整的实现方式: ### 获取 `List<T>` 对象的属性名称 ```csharp using System; using System.Collections.Generic; using System.Reflection; public class Student { public int StudentID { get; set; } public string StudentName { get; set; } } public class Program { public static void Main() { // 创建并初始化一个列表 List<Student> stuList = new List<Student> { new Student { StudentID = 10001, StudentName = "aaa" }, new Student { StudentID = 10002, StudentName = "bbb" } }; // 获取列表中对象的类 Type type = typeof(Student); // 获取所有公共属性 PropertyInfo[] properties = type.GetProperties(); // 输出属性名称 Console.WriteLine("列名(属性名称):"); foreach (PropertyInfo property in properties) { Console.WriteLine(property.Name); } } } ``` ### 输出结果: ``` 列名(属性名称): StudentID StudentName ``` ### 说明: - `typeof(T)` 获取 `T` 的 `Type` 对象。 - `GetProperties()` 返回类的所有公共属性信息数组。 - 遍历 `PropertyInfo[]` 数组可以获取每个属性的名称、类、值等信息。 ### 使用方法扩展通用性 如果希望该方法适用于任意类的 `List<T>`,可以将其封装为一个方法: ```csharp public static List<string> GetPropertyNames<T>() { List<string> propertyNames = new List<string>(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo property in properties) { propertyNames.Add(property.Name); } return propertyNames; } ``` 调用方式如下: ```csharp List<string> columnNames = GetPropertyNames<Student>(); foreach (string name in columnNames) { Console.WriteLine(name); } ``` 这种方法可以用于任何类对象,如 `Student`、`Person`、`Product` 等,具备良好的通用性和扩展性。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值