返回相同对象的类中的泛型方法

时间:2018-07-26 05:50:22

标签: c# asp.net generics

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

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

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

使用泛型有可能吗?还是通过其他任何方式使此操作简单高效?

请参见下面的示例代码。

 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 对象中替换硬编码的值。有可能吗?

5 个答案:

答案 0 :(得分:2)

如果可以将TeacherStudent都做成Customer,并且这两个类共享相同的数据才能成为Customer,那会更好将这些属性提取到基类或接口中。

例如:

public class Person
{
}

public class Student : Person
{
}

public class Teacher : Person
{
}

public static Customer CreateCustomer(Person data)
{

}

答案 1 :(得分:1)

有可能,但您需要提供有关T的更多信息,并更改返回类型:

public T Create<T>(T data) where T : class
{
    return new someType() as T;
}

答案 2 :(得分:1)

您可以从“客户”类继承“老师”和“学生”。 现在,客户必须包含两个类的通用信息

this.setState

然后您可以将老师和学生视为客户。

abstract class Customer {...}
class Teacher : Customer {...}
class Student : Customer {...}

Api.Call应该看起来像这样:

Customer c1 = new Student();
Customer c2 = new Teacher();

Api.Call(c1);
Api.Call(c2);

答案 3 :(得分:1)

您可以使用if接口或基类,该接口或基类应具有Customer类具有的所有属性。可以将其他属性放在派生类中。然后,您的方法将需要基类或接口。

由于您已经提到要调用API并发布此JSON,因此您可能还想看看NewtonSoft的JsonPropertyAttribute(假设您正在使用它)。这样,您甚至不需要创建Customer对象。您可以简单地修饰要以JSON格式序列化的类。 HTH

答案 4 :(得分:1)

首先编写如下的通用类

public class CustomerService<T> where T : class
    {    
        public static Customer CreateCustomer(T data)
        {
            Customer customer = new Customer();

            if (typeof(T) == typeof(Student))  //We just check here is data comes from api is of type Student
            {
                Student student = (Student)(object)data; //then cast this data to Student

                customer = new Customer()
                {
                    CustomerNo = student.StudentID, // Convert.ToInt32(student.StudentID),
                    CustomerName = student.FirstName,

                    //Assign all your remaining customer properties with desired values
                    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"
                    }
                };
            }

            if (typeof(T) == typeof(Teacher))  //We just check here is data comes from api is of type Teacher
            {
                Teacher teacher = (Teacher)(object)data; //then cast this data to Teacher 

                customer = new Customer()
                {
                    CustomerNo =  teacher.TeacherID,  // Convert.ToInt32(teacher.TeacherID),
                    CustomerName = teacher.FirstName,

                    //Assign all your remaining customer properties with desired values
                    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;
        }


    }

您可以根据需要在上述方法中使用if-if或if-else-if。

通过api控制器操作(如

)调用CreateCustomer通用方法

学生数据或老师数据来自您的前端

 [HttpPost]
 //public IHttpActionResult GetCustomer([HttpPost]Teacher teacher)
 public IHttpActionResult GetCustomer()
    {
        Teacher teacher = new Teacher { TeacherID = 12, FirstName = "Vijay" };  //this teacher data comes from front end or from caller of this api
        Customer customer1 = CustomerService<Teacher>.CreateCustomer(teacher);            

        return Ok(customer1);
    }

OR

 [HttpPost]
 //public IHttpActionResult GetCustomer([HttpPost]Student student)
 public IHttpActionResult GetCustomer()
    {           
        Student student = new Student { StudentID = 11, FirstName = "Kunal" };  //this student data comes from front end or from caller of this api
        Customer customer2 = CustomerService<Student>.CreateCustomer(student);

        return Ok(customer2);
    }

结果

教师为客户:

enter image description here

学生客户:

enter image description here