c# - 直接访问属性与通过反射访问属性的影响有多大?
问题描述
假设您有一个如下所示的类:
public class Test
{
public string prop {get;set;}
public string prop2 {get;set;}
public string prop3 {get;set;}
public string prop4 {get;set;}
public string prop5 {get;set;}
public string prop6 {get;set;}
public string prop7 {get;set;}
public string prop8 {get;set;}
public string prop9 {get;set;}
public string prop10 {get;set;}
public string prop11 {get;set;}
public string prop12 {get;set;}
public int count{get;set;}
}
我正在编写一个方法,该方法需要在某些时候仅从此类中获取 2-4 个属性,然后执行一些操作(无论选择哪个属性,这将始终相同)。为了避免基本上多次复制/粘贴相同的确切代码(即重复 //do stuff 部分,对于每个 switch 案例),我写了这样的东西:
public static DataTable GetTop(currenctCondition)
{
DataTable res = null;
List<Test> appo = GetAllTests();
string[] propToGet = null;
switch (currenctCondition)
{
case condition1:
propToGet = new string[] { "prop1", "prop2" };
break;
case condition2:
propToGet = new string[] { "prop3", "prop4" };
break;
case condition3:
propToGet = new string[] { "prop5", "prop6" };
break;
case condition4:
propToGet = new string[] { "prop7", "prop8", "prop9", "prop10" };
break;
}
foreach(Test c in appo)
{
foreach(string prop in propToGet)
{
string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();
// do stuff
}
}
return res;
}
基本上,为了使代码更具可读性和易于维护,我构建了一个字符串数组,其中包含我必须访问的属性的名称,并使用反射来获取属性值:
string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();
当然,这比直接访问我需要的属性要慢,但我想知道这个选择的影响有多大。考虑到它List<Test> appo
可能非常小,但也非常非常大,范围从 0 到(可能在非常罕见的情况下)数百万个元素。
为了得到appo
我需要在 MySQL 上做查询,所以我的理论是这个操作总是会更耗时,使得使用反射的性能损失毫无意义。我将尝试对此进行测试,但是设置会花费我一些时间,因此我想从在该领域比我更有经验的人那里获得一些初步信息
解决方案
推荐阅读
- c# - 弹出窗口关闭后,应刷新主页以加载更改的数据
- android - Android Beacon Library not seeing any beacons
- swift - Change barbutton image
- mysql - How to take some rows in the manual order and then rest in the regular way
- url - 当 URL 包含下划线时,松弛消息“链接按钮”不显示
- jquery - How to assign dynamically fetched variable to HREF, Jquery, laravel
- api - How to compose requests for communication between Java back-end and 3rd party GraphQL API?
- google-cloud-platform - 使用部署管理器的 GKE 抢占式虚拟机
- c - 使用递归找到方程的所有解
- asp.net-mvc - 如何显示来自数据库的部分文本加粗/下划线