C#で書いたカスタム属性をVB(.net)でも書いてみる
VBを使い慣れない私が、カスタム属性クラスを適用するテストコードをC#で書いた後、そのコードVBに書き直してみただけの記事です。
//文字列を保持するだけの属性 public class TestAttribute : Attribute { private string val; //属性のコンストラクタ public TestAttribute(string testValue) { val = testValue; } //コンストラクタで入れた文字列を返すプロパティ public string Value { get { return val; } } } //Test属性を適用したクラス [Test("TestValue")] public class TestClass { } class Program { static void Main(string[] args) { //TestClassに指定されたTestAttributeを取得 var att = (TestAttribute)Attribute.GetCustomAttribute(typeof(TestClass), typeof(TestAttribute)); //TestAttributeのValueを取得 Console.WriteLine(att.Value); } }
上記処理をVB(Visual Studio 2015)で書き直してみます。
'文字列を保持するだけの属性 Public Class TestAttribute Inherits System.Attribute Private val As String '属性のコンストラクタ Public Sub New(ByVal testValue As String) val = testValue End Sub 'コンストラクタで入れた文字列を返すプロパティ Public ReadOnly Property Value() As String Get Return val End Get End Property End Class 'Test属性を適用したクラス <Test("TestValue")> Public Class TestClass End Class Module Module1 Sub Main() 'TestClassに指定されたTestAttributeを取得 Dim att As TestAttribute = Attribute.GetCustomAttribute(GetType(TestClass), GetType(TestAttribute)) 'TestAttributeのValueを取得 Console.WriteLine(att.Value) End Sub End Module
書いてみた結果、継承、コンストラクタ、プロパティ定義やら、C#とVBでの書き方の違いを見比べられて少し良いなと思いました。