The parameter type C #, returns the attribute value corresponding to a class

This is a recent development, there simply record what

Here there is a class, this class is very simple to demonstrate

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

Above this class, different properties may be returned corresponding to the class, such as OneClass().StudentDbreturns a Studentclass OneClass().TeacherDbreturns a Teacherclass.
Then in the GetData()process, according to the incoming class, to obtain the corresponding return type
, for example, passing a Student class I

public object GetData(Student t)

Then it should be returnedStudent

return OneClass().StudentDb

Be embodied using the following generic

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; }
}
Published 62 original articles · won praise 68 · views 160 000 +

Guess you like

Origin blog.csdn.net/ZUFE_ZXh/article/details/100016082