【问题标题】:Expose generic property in c#在 C# 中公开泛型属性
【发布时间】:2020-03-27 09:17:49
【问题描述】:

我需要直接公开我的通用类属性。请参阅下面的代码

namespace ConsoleApp2
{
    public class KTEST<T>
    {
        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public T Filter { get; set; }

    }

    public class Request
    {
        public int CountryId { get; set; }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            KTEST<Request> kTESTRequest = new KTEST<Request>();

            kTESTRequest.PageNumber = 1;
            kTESTRequest.PageSize = 20;

            kTESTRequest.Filter.CountryId = 1;
        }
    }
}

现在,如何在不使用“过滤器”的情况下获取 countryId 属性。 我需要使用 kTESTRequest.CountryId 而不是 kTESTRequest.Filter.CountryId

你能帮我解决这个问题吗?

【问题讨论】:

  • 不可能
  • 除非你有一个你做不到的接口,否则为什么你真的需要这样做?
  • @BuntyChoudhary:“它可以是任何东西”是尽可能模糊的。你目前的期望是矛盾的。一方面,你告诉我“它可以包含任何东西”。另一方面,您的代码告诉我过滤器肯定有 CountryId 属性。这是一个或另一个。这要么是 XY 问题,要么是对泛型的深刻误解。我还在写一个答案,但在你没有具体信息的情况下,这将是一个理论上的答案。
  • @BuntyChoudhary:好的,所以二等舱也有 CountryId。每个过滤器都会有一个国家 ID 吗?您是否也希望使用过滤器中的 StateId ?当您使用原始请求类并尝试访问该原始请求类中不存在的 StateId 时,代码会发生什么情况?在编写可以处理所有这些情况的代码之前,您确实需要考虑在这些情况下要发生什么。
  • 为什么 KTEST 应该是通用的,为什么不能将所有过滤器作为属性放在 KTEST 类中?

标签: c#


【解决方案1】:

这样做的唯一方法是使用interface

给定

public interface IMyInterface
{
    public int CountryId{ get; set; }
}

用法

public class KTEST<T>  where T : IMyInterface
{
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public T Filter { get; set; }
    public int CountryId => Filter.CountryId
}

要求

public class Request : IMyInterface
{
    public int CountryId { get; set; }
}

【讨论】:

  • 但是如果你有另一个请求,比如 public class Request1 { public int CountryId { get;放; } 公共 int StateId { 获取;放; } 公共 int CityId { 获取;放; } } 我们将如何处理它。
  • @BuntyChoudhary 添加接口,如果你不能,那么你就不能做你想做的事
  • 无法添加多个接口,需要将KTEST设为泛型类
  • 学究式地,接口不是唯一的方式。基类也同样有效。它并没有真正改变答案,但它确实在某种程度上重新构建了对如何实现这一点的期望。
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 2020-08-06
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多