简体   繁体   中英

Get Attribute from object; 'Attribute' does not contain a definition for 'GetCustomAttribute'

I've been using the guides on microsofts website but unable to put them into practice. I've been using this code here:

public static async Task<T> LoadObject<T>(string objectId) where T : DBObject
{
    ...
    TestAttribute MyAttribute = (TestAttribute)System.Attribute.GetCustomAttribute(typeof(T), typeof(TestAttribute));
    ...
}

But this causes the error below; Attribute only seems to have the methods Equals and ReferenceEquals . I'm thought I might be missing a reference but I've included all that was in the samples.

Error CS0117: 'Attribute' does not contain a definition for 'GetCustomAttribute' (CS0117) (TestProject)

Because you're using Xamarin, you're running the Mono Framework which means you don't have access to the full .Net Framework library as you might expect. One of the changes is reflection, and you need to change your code to this:

TestAttribute MyAttribute = typeof(T).GetTypeInfo().GetCustomAttribute<TestAttribute>();

You can't find it because it hasn't been implemented there. See below decompiled System.Runtime.dll.

namespace System
{
  [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
  public abstract class Attribute
  {
    [SecuritySafeCritical]
    public override bool Equals(object obj)
    {
       return false;
    }

    [SecuritySafeCritical]
    public override int GetHashCode()
    {
       return 0;
    }
  }
}

Use something like

typeof(T).GetTypeInfo().GetCustomAttribute<>()

instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM