简体   繁体   中英

How Do I Access Class Property From Variable in C#?

I have created several classes to model JSON data returning from an API. The section with relevance looks like:

public class ErrorClass
    {
        public string status { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string? unknown_properties { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string? invalid_coordinates { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string? location_error { get; set; }
    }

Some of these error properties will only show up when an error is present in the JSON to be modeled (null values ignored). I want to setup a helper to handle errors. This will check to see if certain values were populated in the object and add those to error messages respectively. I have a list of property names potentially belonging to an object of a class. I want to loop through the list of strings and check to see if they have a value in the current object. My issue is that I am unsure how to do something like:

    public class ErrorsHelper
    {
        string[] badRequestErrors = {"invalid_coordinates", "location_error"};
        public void Process_Errors(dynamic errors)
        {
            for (int i = 0; i < badRequestErrors.Length; i++)
            {
                var badRequestError = badRequestErrors[i];
                if (errors.badRequestError[i])
                {
                    // Add to list, etc.
                }
            }
        }
    }

Because the compiler looks for a property of the variable name instead of the value of that variable. How can I look for a property name in a C# object in this fashion?

Thank you in advance!

Using Reflection, this will return all properties annotated with JsonPropertyAttribute .

var properties = typeof(ErrorClass)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => p.GetCustomAttribute<JsonPropertyAttribute>() != null)
                .ToList();

You can access their names like this:

foreach (var propertyInfo in properties)
            {
                Console.WriteLine(propertyInfo.Name);
            }

You can get their value by:

var propertyValue = propertyInfo.GetValue(obj);

The high-level answer is that you would use reflection . see: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection

Reflection is often discouraged, but it is a valid approach. See:

https://softwareengineering.stackexchange.com/questions/143205/reflection-is-using-reflection-still-bad-or-slow-what-has-changed-with-ref

For some discussion. A couple of points: it is generally 'slower' (though often not practically), and it can bypass compiler checks (possibly introducing errors).

If any one of your errors is 'bad' enough to stop the whole process, you could also yield return in your error checker, and simply check all of the various error types in serial, provided there aren't too many error types.

You can get class properties using below code:

PropertyInfo[] propertyInfos = typeof(ErrorClass).GetProperties();
        
Array.ForEach(propertyInfos, property => 
Console.WriteLine("Property Name is :" + property.Name));

I never actually found a solution for this problem. The issue was that .getType() only returns the class type of the object and so running the provided solutions on it would only give the available properties and not those that were actually non-null in the object.

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