VB.. NET公共属性在一行上
本文关键字:一行 NET 属性 VB | 更新日期: 2023-09-27 18:09:26
是否有任何方法可以将公共属性放在VB的单行上?像c#一样。NET吗?每次我尝试将所有内容移到一行时,我都会得到一堆错误。
c#:public void Stub{ get { return _stub;} set { _stub = value; } }
VB。净
Public Property Stub() As String
Get
Return _stub
End Get
Set(ByVal value As String)
_stub = value
End Set
End Property
感谢编辑:我应该澄清一下,我使用的是VB 9.0。
您可以在VB 10和c#中使用自动实现的属性,两者都将比您展示的c#更短:
public string Stub { get; set; }
Public Property Stub As String
对于不重要的属性,听起来你可以将所有内容放在VB中的一行中-但是因为它有点冗长,我怀疑你最终会用很长的一行,损害可读性…
可以
Public Property Stub() As String : Get : Return _stub : End Get : Set(ByVal value As String) :_stub = value : End Set : End Property
,你甚至可以使它更短,根本不可读;-)
Public Property Stub() As String:Get:Return _stub:End Get:Set(ByVal value As String):_stub = value:End Set:End Property
如果您愿意使用稍微不同的语法,并链接到c#程序集(或使用IL),则可以在一行中定义一个变量,其行为类似于属性。
已在VS2017和。net 4.7.2中测试。
c#代码(目前在VB.Net中不可用):
public class Propertor<T>
{
public T payload;
private Func<Propertor<T>, T> getter;
private Action<Propertor<T>, T> setter;
public T this[int n = 0]
{
get
{
return getter(this);
}
set
{
setter(this, value);
}
}
public Propertor(Func<T> ctor = null, Func<Propertor<T>, T> getter = null, Action<Propertor<T>, T> setter = null)
{
if (ctor != null) payload = ctor();
this.getter = getter;
this.setter = setter;
}
private Propertor(T el, Func<Propertor<T>, T> getter = null)
{
this.getter = getter;
}
public static implicit operator T(Propertor<T> el)
{
return el.getter != null ? el.getter(el) : el.payload;
}
public override string ToString()
{
return payload.ToString();
}
}
然后在VB程序中,例如:
Private prop1 As New Propertor(Of String)(ctor:=Function() "prop1", getter:=Function(self) self.payload.ToUpper, setter:=Sub(self, el) self.payload = el + "a")
Private prop2 As New Propertor(Of String)(ctor:=Function() "prop2", getter:=Function(self) self.payload.ToUpper, setter:=Sub(self, el) self.payload = el + "a")
public Sub Main()
Console.WriteLine("prop1 at start : " & prop1.ToString)
Dim s1 As String = prop1
Console.WriteLine("s1 : " & s1)
Dim s2 As String = prop1()
Console.WriteLine("s2 : " & s2)
prop1() = prop1()
Console.WriteLine("prop1 reassigned : " & prop1.ToString)
prop1() = prop2()
Console.WriteLine("prop1 reassigned again : " & prop1.ToString)
prop1() = "final test"
Console.WriteLine("prop1 reassigned at end : " & prop1.ToString)
end sub
结果是:
prop1 at start : prop1
s1 : PROP1
s2 : PROP1
prop1 reassigned : PROP1a
prop1 reassigned again : PROP2a
prop1 reassigned at end : final testa