お世話になります。
前提・実現したいこと
現在、属性を利用したプログラムをVB.NETで作成しています。
特に問題なくできたと思っていたのですが、以下のような問題が生じ、期待した動作(属性を継承しない)を実現できません。
発生している問題
AttributeUsage属性のInherited引数をfalseに設定しているが、継承先で属性がそのまま継承されている。
該当のソースコード
簡略化したソースコードを載せておきます。
<AttributeUsage(AttributeTargets.Property, Inherited:=False)> Public Class IdAttribute Inherits Attribute End Class Public Class Parent <Id()> Public Property parentId As Integer End Class Public Class Child Inherits Parent <Id()> Public Property childId As Integer End Class Module Module1 Sub Main() Console.WriteLine("Parent") Dim parent As New Parent For Each propInfo In parent.GetType().GetProperties() If propInfo.IsDefined(GetType(IdAttribute), False) Then Console.WriteLine("inherited: " & propInfo.Name) End If Next Console.WriteLine("") Console.WriteLine("Child") Dim child As New Child For Each propInfo In child.GetType().GetProperties() If propInfo.IsDefined(GetType(IdAttribute), False) Then Console.WriteLine("inherited: " & propInfo.Name) End If Next End Sub End Module
上記を実行すると
Parent
inherited: parentId
Child
inherited:childId
inherited:parentId ←属性が継承されている
と表示されます。マニュアルのAttributeUsageなどを見た限り、ChiledクラスではparentIdは表示されないように思えます。
試したこと
同様にC#でも試してみた結果、C#では期待した動作をします。(ChildクラスでparentIdが表示されない)
C#のソースコードも載せておきます。
[AttributeUsage(AttributeTargets.Property, Inherited = false)] public class IdAttribute : Attribute { } public class Parent { [Id] public int parentId { get; set; } } public class Child { [Id] public int childId { get; set; } } class Program { static void Main(string[] args) { Console.WriteLine("Parent"); var parent = new Parent(); foreach (var propInfo in parent.GetType().GetProperties()) { if (propInfo.IsDefined(typeof(IdAttribute), false)) { Console.WriteLine("inherited: " + propInfo.Name); } } Console.WriteLine("Child"); var child = new Child(); foreach (var propInfo in child.GetType().GetProperties()) { if (propInfo.IsDefined(typeof(IdAttribute), false)) { Console.WriteLine("inherited: " + propInfo.Name); }; } } }
上記を実行すると
Parent
inherited: parentId
Child
inherited: childId
と表示されます。
補足情報(FW/ツールのバージョンなど)
環境は
Windows7
VisualStudio2010
TargetFrameWork 4.0
です。
また以下の環境でも現象を確認しております。
windows7
VisualStudio2017
TargetFrameWork 4.5.2
個人的には最初バグかな?と思ったのですが、調べてみてもそういった情報が出てこないので、なにか勘違いをしているのかなと思っています。(が、わからない。プロパティ関連でなにか勘違いしているのでしょうか?)
もしなにか知っておられたら教えて頂けないでしょうか?
よろしくお願いします。
追記:C#のコードの方でChildクラスがPanretクラスを継承していませんでした。
継承した結果、VB.NETと同じ結果となりました。
ということはそもそもこういう動作になるのが正常ということなのでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/12 21:01