C#根据参数类型,返回一个类对应的属性值

这是最近开发的情况,这里简单记录一下

有下面一个类,为了演示这个类很简单

public class OneClass
{
	public Student StudentDb { get; set; }
	
	public Teacher TeacherDb { get; set; }
	
	public Location LocationDb { get; set; }
	
	......//表示有很多这样的属性
	
	public Equip EquipDb { get; set; }
}

上面这个类中,不同的属性可以返回对应的类,比如OneClass().StudentDb就返回一个Student类,OneClass().TeacherDb就返回一个Teacher类。
然后在GetData()方法中,要根据传入的类,得到对应的返回类
比如,我传入一个Student类

public object GetData(Student t)

那么返回的就应该是Student

return OneClass().StudentDb

下面使用泛型来具体实现

public static object GetData<T>() where T : class, new()
{
	//T代表传入的类型,比如GetData(Student)就表示传入了Student类
    //获取类型
    Type EntityType = typeof(T);     

    //获取要获取属性的类--这里是OneClass
    Type DbE = typeof(OneClass);   

    try
    {
        //获取当前属性对象
        PropertyInfo property = DbE.GetProperty(EntityType.Name + "Db");

        //返回对象对应属性的值-并使用`as`来转换为传入的类对象
        var result = property.GetValue(new DbEntities()) as T;
		
		//这里的result就是返回的属性
		return result;
    }
    catch { throw; }
}
发布了62 篇原创文章 · 获赞 68 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/ZUFE_ZXh/article/details/100016082