类定义中能否使用If语句根据公共变量条件声明属性
结论
不能直接实现你写的这种在类定义内部通过If语句条件性声明属性的效果。
VB.NET是静态类型语言,类的成员(属性、方法、字段等)属于类型定义的一部分,必须在编译阶段完全确定,无法在程序运行时根据公共变量的值动态修改类的结构,你写的把If判断嵌在类成员声明层的写法不符合VB语法规则,无法通过编译。
可行替代方案
你可以根据自己的实际场景选下面几种实现方式:
方案1:同时声明两个属性,通过逻辑控制属性的有效性
把两个可能用到的属性都定义在类里,结合公共变量的值控制属性的读写行为,不需要的属性返回空值即可:Public Class SomeDude Property strName As String Private _birthDate As Date? Private _birthStr As String Public Property datBirth As Date? Get Return If(strPublicVariable = "foo", _birthDate, Nothing) End Get Set(value As Date?) If strPublicVariable = "foo" Then _birthDate = value End Set End Property Public Property strBirth As String Get Return If(strPublicVariable <> "foo", _birthStr, Nothing) End Get Set(value As String) If strPublicVariable <> "foo" Then _birthStr = value End Set End Property End Class这个方案实现最简单,但类对外始终暴露两个属性,调用时需要自行判断该访问哪个属性。
方案2:使用动态对象实现运行时增减属性
引用System.Dynamic命名空间下的ExpandoObject,可以在运行时动态给对象添加属性,完全匹配你要的条件判断逻辑:' 需提前导入Imports System.Dynamic Dim dude As Object = New ExpandoObject() dude.strName = "张三" If strPublicVariable = "foo" Then dude.datBirth = #2000-1-1# Else dude.strBirth = "2000年1月1日" End If这个方案灵活性最高,但失去了强类型的编译时检查和智能提示,属性名写错只会在运行时报错,适合对灵活性要求高、对类型安全要求低的场景。
方案3:抽象基类+多实现(工程化推荐方案)
定义公共基类存放共有属性,再根据不同的属性需求派生两个子类,使用时根据公共变量的值实例化对应子类即可:Public MustInherit Class BaseDude Property strName As String End Class Public Class DateBirthDude Inherits BaseDude Property datBirth As Date End Class Public Class StrBirthDude Inherits BaseDude Property strBirth As String End Class ' 调用逻辑 Dim currentDude As BaseDude If strPublicVariable = "foo" Then currentDude = New DateBirthDude() With {.datBirth = #2000-1-1#} Else currentDude = New StrBirthDude() With {.strBirth = "2000年1月1日"} End If这个方案完全符合静态类型的设计规范,保留了编译时类型检查和智能提示,是正式项目里优先选择的实现方式。
内容的提问来源于stack exchange,提问作者8oris
相关产品推荐
相关产品推荐

