有没有什么方法可以像在C#中一样将公共属性放在VB.NET中的一行?每次我尝试将所有内容都移到一行时,我会收到一堆错误。
C#:
public void Stub{ get { return _stub;} set { _stub = value; } }
VB.NET
Public Property Stub() As String
Get
Return _stub
End Get
Set(ByVal value As String)
_stub = value
End Set
End Property
由于
编辑:我应该澄清一下,我正在使用VB 9.0。
答案 0 :(得分:11)
您可以在VB 10和C#中使用自动实施的属性,这两个属性都会比您显示的C#短:
public string Stub { get; set; }
Public Property Stub As String
对于非平凡的属性,听起来你可以放弃将所有内容放在VB中的一行 - 但因为它更冗长,我怀疑你最终会有一个很长的线,伤害可读性......
答案 1 :(得分:2)
是的,你可以
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
答案 2 :(得分:0)
如果愿意使用稍微不同的语法,就可以在一行上定义一个行为类似于属性的变量,并链接到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