[英]Converting object to specified class
我正在嘗試創建一個全局接口,它將接收不同類型的 class。我該如何轉換。
我如何傳遞並獲得 object 並將其轉換為特定的 class
public void Generate()
{
Student s = new Student
{
Id = Entry; // binded entry
};
var student = method("Student",s)
if(student != null)
{
//binded labels
Name = Student.Name;
Gender = Student.Gender;
Age = Student.Age;
Course = Student.Course;
}
}
public async Task<object> method(string condition,object obj)
{
switch(condition)
{
case "Student":
var student = get from database where id= obj.id;
return student;
case "Teacher":
var teacher = get from database where id= obj.id;
return Teacher;
}
}
問題是如何將傳遞的 object 轉換為特定類型的 class 以將其用於查詢數據庫。 與返回值相同
您可以將其轉換為您想要的特定 object
case "Student":
var student = (obj as Student);
var res = get from database where id= student?.id;
return res;
在調用此方法后,您必須再次執行此操作:
var student = (method("Student",s).Result) as Studednt;
您可以在“方法”上使用模式匹配來轉換傳遞的 object 以將其用於查詢數據庫
public async Task<object> method(object obj)
{
switch (obj)
{
case Student student:
return (Student)null; // return get from database where id = student.id;
case Teacher teacher:
return (Teacher)null; // return get from database where id = teacher.id;
default:
break;
}
}
然后
var s = new Student() { Id = 1 };
var result = await method(s);
if(result is not null && result is Student student)
{
//binded labels
// Name = Student.Name;
// Gender = Student.Gender;
// Age = Student.Age;
// Course = Student.Course;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.