簡體   English   中英

兩個泛型有直接聯系,如何避免重復輸入?

[英]Two generic types have direct connection, how to avoid repeated input?

public interface IService<T> where  T : IComparable<T> { }
public class CommonController<S, T> where S : IService<T>, new() where T : IComparable<T> { }

public class CustomerService : IService<int> { }

// Correct
public class CustomerController : CommonController<CustomerService, int> { }

// Confict, from CustomerService, T is int, but the second type is long
public class CustomerController : CommonController<CustomerService, long> { }

很明顯可以從 CustomerService 中猜出第二種類型“int”。 是否可以刪除第二個泛型類型以及如何刪除?

您可以通過執行以下操作消除T的重復性:

public static class Foo<T> where T : IComparable<T>
{
    public interface IService { }
    public class CommonController<S> where S : IService, new() { }
    public class CustomerService : IService { }
    public class CustomerController : CommonController<CustomerService> { }
}

但是,如果您需要在Foo<T>之外定義CustomerServiceCustomerController ,那么您基本上會回到第一方。

public static class Foo<T> where T : IComparable<T>
{
    public interface IService { }
    public class CommonController<S> where S : IService, new() { }
}

public class CustomerService : Foo<int>.IService { }

public class CustomerController : Foo<int>.CommonController<CustomerService> { }

所以答案是,基本上,不。

暫無
暫無

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

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