gpt4 book ai didi

c# - 返回相同对象的类中的通用方法

转载 作者:行者123 更新时间:2023-11-30 14:22:08 24 4
gpt4 key购买 nike

我有一个类,我想向该类添加一个泛型方法,该方法每次调用时都返回相同的对象。但是方法参数可以是不同的对象。无论参数是什么,方法都应该始终返回相同的对象类型。

创建此方法的目的是我想调用一个 API 并且我需要将 JSON 序列化对象发送给它。每次我调用 API 时,它都会在他们的服务中创建一个新客户。 API 服务只有一个客户类型对象。但在我的应用程序中,我有两种类型的对象(例如:学生、教师)API 不关心我发送的是学生对象还是教师对象。从 API 的角度来看,这两个对象都是客户。

因此,每当我调用 API 时,我都需要创建通用客户对象以传递给 API。但是我的应用程序中有两个对象,我想编写一个方法来接受 Student 和 Teacher 对象,但返回一个客户对象。

这对泛型来说可能吗?或者有什么其他方法可以使这变得简单高效?

请参阅下面的示例代码。

 public static Customer CreateCustomer<T>(T data)
{
var customer = new Customer()
{
CustomerNo = 1,
CustomerName = "Test",

CustomerContact = new CustomerContact()
{
CustomerContactName = "Test",
CustomerContactEmail = "test@test.com",
CustomerContactPhone = "011111111"
},
PrimaryAddress = new CustomerAddress()
{
Street = "Hill street",
ZipCode = "16962",
City = "New york",
Country = "USA"
},
BillingAddress = new CustomerAddress()
{
Street = "Hill street",
ZipCode = "16962",
City = "New york",
Country = "USA"
}
};
return customer;
}

public class Teacher
{
public long TeacherID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public Subject Subjects { get; set; }

public string Email{ get; set; }

public string ContactNO{ get; set; }

public Address PrimaryAddress { get; set; }

public Address SecondaryAddress { get; set; }
}

public class Student
{
public long StudentID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public int Age { get; set; }

public string Email{ get; set; }

public string ContactNO{ get; set; }

public Address PrimaryAddress { get; set; }

public Address SecondaryAddress { get; set; }

public string Grade { get; set; }

public int Level { get; set; }
}

T data 可以是 Student 或 Teacher。我想替换此 data 对象中的硬编码值。可能吗?

最佳答案

如果 TeacherStudent 都可以变成 Customer 并且这两个类共享相同的数据以成为 Customer,最好将这些属性提取到基类或接口(interface)中。

例如:

public class Person
{
}

public class Student : Person
{
}

public class Teacher : Person
{
}

public static Customer CreateCustomer(Person data)
{

}

关于c# - 返回相同对象的类中的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51531823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com