【问题标题】:How to limit a Type type to a specific types subset in C#如何将 Type 类型限制为 C# 中的特定类型子集
【发布时间】:2017-08-10 20:45:41
【问题描述】:

Type 类型的变量可以包含任何类型。我需要的是一个只能包含继承特定类并实现特定接口的类型的变量。如何指定?我尝试将变量声明为

Type: MyClass, IMyInterface theTypeVariable;

作为

Type<MyClass, IMyInterface> theTypeVariable;

但两者都不起作用。

正确的方法是什么?

例如

class A {...}

class B {...}

interface IC {...}

interface ID {...}

class E: B, IC {...}

class F: B, IC, ID {...}

class G: ID {...}

...

// This following line invalid actually,
// so it is pseudocode of a kind
// the syntactically and semantically correct form of this is the question
Type: B, IC theTypeVariable; // or Type<B, IC> theTypeVariable // perhaps

theTypeVariable = typeof(E); // This assignment is to be valid.

theTypeVariable = typeof(F); // This assignment is to be valid.

theTypeVariable = typeof(A); // This assignment is to be invalid.

theTypeVariable = typeof(B); // This assignment is to be invalid.

theTypeVariable = typeof(IC); // This assignment is to be invalid.

theTypeVariable = typeof(G); // This assignment is to be invalid.

举个更明确的例子:我可能想要声明一个类型变量,它只能包含扩展 List&lt;T&gt; 并实现 IDisposable 的任何类型(一次性 T 列表,而不是一次性列表)。

例如我将实现DisposableList&lt;T&gt;: List&lt;T&gt;, IDisposableAnotherDisposableListImplementation&lt;T&gt;: List&lt;T&gt;, IDisposable 类,并且我想要一个能够存储typeof(DisposableList&lt;Foo&gt;)typeof(AnotherDisposableListImplementation&lt;Foo&gt;) 但不能存储typeof(Foo)typeof(List&lt;Foo&gt;) 的变量。

【问题讨论】:

  • 这里根本不清楚你在问什么。
  • @DavidG 好的,请稍等,我将添加示例。感谢您的反馈。
  • 你指的是泛型吗?
  • 所以不,你问的是不可能的,也不清楚你为什么要这样做。这对我来说有点像XY Problem
  • Type 变量可以包含任何 Type 值,因为 Int32 变量可以包含任何 Int32 值。处理上没有区别

标签: c# inheritance reflection types syntax


【解决方案1】:

Type 包含有关类型的元数据;它是反射 API 的一部分。这是无效的:

Type x = 5;
Type y = "Hello Sailor!";

要拥有一个类型U,它是T 的子类型并实现接口I,您可以使用泛型:

... Foo<U>(...)
where U : T, I
{
  U myvar;
}

你可以这样创建一个新类型:

class MyType : MyClass, IMyInterface
{
  private MyClass A;
  private IMyInterface B;

  private MyType(MyClass a, IMyInterface b)
  {
    A = a;
    B = b;
  }

  public static MyType Create<U>(U x)
  where U : MyClass, IMyInterface
  {
    return new MyType(x, x);
  }

  // Implementations of MyClass and IMyInterface
  // which delegate to A and B.

}

现在MyType 类型的变量是MyClassIMyInterface 的子类型。

【讨论】:

    【解决方案2】:

    我相信这就是你要找的东西

     public class EstentedList<Type> where Type:List<T>,IDisposable
     {
    
     }
    

    您可以将此类用作变量的类型

    【讨论】:

    • 如何阻止特定类型存储在Type 变量中?
    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多