【问题标题】:Is there a way of strictly enforce the type that can be used. (Very Explict Casting)有没有办法严格执行可以使用的类型。 (非常明确的铸造)
【发布时间】:2012-03-10 22:52:46
【问题描述】:

有没有办法“严格”限制或强制使用可以使用的类型。

S <: T

类似

Method( value As T ) ' Any Type of T including subtypes of T  
Method( value Is T ) ' Only take a T not a subtype of T

我可以在运行时这样做

 If TypeOf value Is T Then

但这是运行时检查,编译时检查会更可取

Option Strict On

这仅将其限制为(隐式)类型扩展 Coerecions。

我希望所有类型强制都必须是显式的。

有可能吗?如果有怎么办?

【问题讨论】:

标签: .net types type-coercion


【解决方案1】:

你的意思是这样的:

private void Method<T>(T mytype) where T: MyClass
{
}

这是可能的解决方案

【讨论】:

【解决方案2】:

不,作为一个类型的用户 - 你对是否接受派生类型没有发言权。如果您是一个类型的所有者,那么您不能通过将您的类标记为sealed 来允许派生类型。

话虽如此,您的请求违反了许多 OOD 原则。如果确实有必要,您可能需要重新考虑您的设计。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    相关资源
    最近更新 更多