簡體   English   中英

如何獲得泛型類中的屬性和值?

[英]How can get Property and the Value in a generic Class?

這是調用函數並創建對象的地方,也許通過這種方式您可以看到我正在嘗試執行的操作

     class Program 
        {

            static void Main(string[] args)
            {

                 //here I create an object and pass the type Person
                var Crud = new Crud<Person>();
                //here I invoke the method Create and pass the object "Person"
                Crud.Create(new Person(Crud.Id) { Name = "Sameone", Age = 24 });
//here I invoke the method again to Create and pass an other object "Person"
                    Crud.Create(new Person(Crud.Id) { Name = "Sameone2", Age = 24 });

               With this method Read() I get the List created back
                var Lista = Crud.Read();
                Lista.ForEach((x) => Console.WriteLine("{0}  {1}",x.Id.ToString(), x.Name));

              /* Here is where my problem starts I'm sending an new object that will replace the object with Id =1 passed by constructor   */
                Crud.Update(new Person(1) { Name = "someone3", Age = 20 });




                Console.ReadKey();
            }
}

這是我嘗試使用此類的地方

//此類是通用的,其中T是已傳遞的“ Person”類型

   public class Crud <T>: ICrud <T> {

      private List <T> List = new List <T> ();

      public MessageError Update(T object) {
    //Here it doesn't work its impossible to get the Id property sense its an generic object at this point
       List.RemoveAll(x => x.Id == t.Id);
       List.Add(t);
       return new MessageError {
        Status = Status.Sucessful
       };
      }
     }

我的代碼中使用的具體類型

 public class Person
    {
        public int Id { get; private set; }
        public string Name { get; set; }
        public int Age { get; set; }
        //Here I set the id for each object
        public Person(int _id)
        {
            Id = _id;
        }
    }

在這里你可以看到界面

 interface ICrud<T>
    {
        MessageError Create(T t);
        List<T> Read();
        MessageError Update(T t);
        MessageError Delete(int Id);
    }

我現在嘗試使用類似但仍然無法正常工作

 List.RemoveAll(x => x.GetProperty("Id") == t.GetProperty("Id"));

我想這就是解決方案

public MessageError Update(T t)
    {
        var type = t.GetType();

        PropertyInfo prop = type.GetProperty("Id");

        var value = prop.GetValue(t);    
        List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
        List.Add(t);
        return new MessageError
        {
            Status = Status.Sucessful
        };
    }

我想也許您只是想走一步。 CRUD代表創建,讀取,更新,刪除。 在這里,您正在創建一些數據,讀取所有內容,然后嘗試將更新直接發送到數據存儲。 您應該做的是,在您的Persons中讀取,更改其一個或多個屬性,然后Crud.Update(person) ,這將知道該Crud.Update(person)需要更新而不是在數據存儲中創建。

實際上,根據實體是否具有其ID值來區分“創建”和“更新”是一種相當正常的做法。 在這種情況下,您的代碼可能如下所示:

class Program 
{
    static void Main(string[] args)
    {
        TestClass testClass = new TestClass();
        testClass.Create();

        var crud = new Crud<Person>();

        // Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
        crud.Create(new Person() { Name = "Someone", Age = 24 });
        crud.Create(new Person() { Name = "Someone2", Age = 24 });

        var list = crud.ReadAll();
        list.ForEach(x => Console.WriteLine("{0} {1}", x.Id, x.Name));

        var person1 = list.Single(x => x.Id == 1);
        person1.Name = "Someone3";
        person1.Age = 20;

        Crud.Update(person1);

        Console.ReadKey();
    }
}

盡管這里需要做進一步的優化。 這會將所有對象從數據存儲區加載到應用程序的內存中,然后將遍歷每個對象,直到找到所需對象為止。 如果正在使用的數據存儲可以為您做到這一點會更好。 在這種情況下,您可以做更多類似var person1 = crud.FindById(1)事情。 有很多其他技術可以解決這個問題,但是我不想讓這個答案進一步復雜化。

public MessageError Update(T t)
    {
/* I used this why to the the property in my last version I get the name of property by Parameter */
        var type = t.GetType();
        PropertyInfo prop = type.GetProperty("Id");

        var value = prop.GetValue(t);    
        List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
        List.Add(t);
        return new MessageError
        {
            Status = Status.Sucessful
        };
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM