泛型类怀疑如何传递对象并获得所需的结果 [英] Generic Class doubt how to pass object and get the desired result

查看:98
本文介绍了泛型类怀疑如何传递对象并获得所需的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在C#中探索Generic类。

我试图将一个对象传递给类Test并且我正在分配 _value 客户对象。



如何在下面的write方法中检索客户对象值?

I am just trying to explore Generic class in C#.
I am trying to pass an object to the class Test and I am assigning the _value the customer object.

How to retrieve the customer object value in write method below?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

    public class Customer
    {

        public int CusomerId { get; set; }
        public string CustomerName { get; set; }
        public int CustomerAge { get; set; }
    }

    public class Test<T>
    {

        T _value;

        public Test(T t)
        {

            _value = t;
        }

//i am trying here to get the customer object from _value which i assigned in _value
//i cant even use foreach in generic class...
        public void write()
        {
       

        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Customer obj = new Customer();
            obj.CusomerId = 1001;
            obj.CustomerAge = 23;
            obj.CustomerName = "Anurag";

            Test<object> T1 = new Test<object>(obj);
            T1.write();
            Console.ReadLine();
        }
    }
}

请帮助我

推荐答案

试试这个:

Try this:
public class Test<T> where T : Customer



其中T:客户确保您只能使用 Customer 类型或从 Customer 派生的类型。



然后,在 Main 方法中更改此行:


where T : Customer makes sure you can only use the type Customer or types derived from Customer.

Then, change this line in the Main method:

Test<Customer> T1 = new Test<Customer>(obj);



更改对象进入客户,否则会出现编译错误。



现在,你将成为能够从泛型类中的 Customer 类访问属性。


Change object into Customer, otherwise you will get a compiler error.

Now, you will be able to access the properties from the Customer class from your generic class.


在write()方法中尝试这个。

对象a = _value;

客户c =(客户)a;

Console.WriteLine(c.CustomerId);

Console.WriteLine(c.CustomerName);

Console.WriteLine(c.CustomerAge);
try this in your write() method
object a = _value;
Customer c = (Customer)a;
Console.WriteLine(c.CustomerId);
Console.WriteLine(c.CustomerName);
Console.WriteLine(c.CustomerAge);


这篇关于泛型类怀疑如何传递对象并获得所需的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆