Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c# - What is an equivalent method to `GetCustomAttributes` for .NETCore (Windows 8 Framework)?

I'm putting together an app that interfaces with Stack API and have been following this tutorial (although old API version it still works). My problem is that when using this within the Windows 8 Store App I'm contrained by the .NETCore Framework which doesn't support the GetCustomAttributes method found below:

    private static IEnumerable<T> ParseJson<T>(string json) where T : class, new()
    {
        var type = typeof (T);
        var attribute = type.GetCustomAttributes(typeof (WrapperObjectAttribute), false).SingleOrDefault() as WrapperObjectAttribute;
        if (attribute == null)
        {
            throw new InvalidOperationException(
                String.Format("{0} type must be decorated with a WrapperObjectAttribute.", type.Name));
        }

        var jobject = JObject.Parse(json);
        var collection = JsonConvert.DeserializeObject<List<T>>(jobject[attribute.WrapperObject].ToString());
        return collection;
    }

My question is two-fold. What exactly does the GetCustomAttributes do and is there an equivalent to this method within the constrains of Windows 8 Store App realm?

question from:https://stackoverflow.com/questions/12814723/what-is-an-equivalent-method-to-getcustomattributes-for-netcore-windows-8-fr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use type.GetTypeInfo(), which then has various GetCustomAttribute methods (via extension methods), or there is .CustomAttributes which gives you the raw information (rather than materialized Attribute instances).

For example:

var attribute = type.GetTypeInfo().GetCustomAttribute<WrapperObjectAttribute>();
if(attribute == null)
{
    ...
}
...

GetTypeInfo() is the pain of .NETCore for library authors ;p

If .GetTypeInfo() doesn't appear, then add a using System.Reflection; directive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...