logo
down
shadow

Accessing object properties from string representations


Accessing object properties from string representations

Content Index :

Accessing object properties from string representations
Tag : chash , By : Jonathan
Date : January 02 2021, 06:48 AM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Accessing object properties from string representations


Tag : chash , By : gorbiz
Date : March 29 2020, 07:55 AM
help you fix your problem After hitting my head against the problem for a while and hoping on a train home last night I decided that I would try and bash out an answer. Using a combination of Jon's pointers and Frederik's use of the PropertyInfo class and keeping the original idea of switching on the underlying object type, this is what I came up with ...
    private void Sort_version2(string propertyName)
    {
        // convert to list
        List<MyClass> myCurrentClass = Items as List<MyClass>;

        string typeOfProperty;
        PropertyInfo pi;

        // sort
        if ((myCurrentClass != null) && (MyClass.HasDetailAndExtract(propertyName, out typeOfProperty, out pi)))
        {
            switch(typeOfProperty)
            {
                case "System.String":
                    myCurrentClass.Sort(delegate(MyClass one, MyClass two)
                                            {
                                                return
                                                    Comparer<string>.Default.Compare(pi.GetValue(one, null).ToString(),
                                                                                     pi.GetValue(two, null).ToString());
                                            });
                    break;

                case "System.Int32":
                    myCurrentClass.Sort(delegate (MyClass one, MyClass two)
                                            {
                                                return
                                                    Comparer<int>.Default.Compare(
                                                        Convert.ToInt32(pi.GetValue(one, null)),
                                                        Convert.ToInt32(pi.GetValue(two, null)));
                                            });
                    break;
                default:
                    throw new NotImplementedException("Type of property not implemented yet");
            }
        }
    }

Accessing string representations of constant field values in java


Tag : java , By : user109127
Date : March 29 2020, 07:55 AM
Any of those help If you can change the class which contains these constants, it would be better to make it an enum with a value() method.
Otherwise, I would suggest building a Map once using reflection, and then just doing map lookups:
Map<Integer, String> valueToStringMap = new HashMap<>();
for (Field field : Foo.class.getFields()) {
    int modifiers = field.getModifiers();
    if (field.getType() == Integer.class && Modifier.isPublic(modifiers)
        && Modifier.isStatic(modifiers)) {
        valueToStringMap.put((Integer) field.get(null), field.getName());
    }
}

Accessing the properties of an object with a string in Swift


Tag : swift , By : jaime
Date : March 29 2020, 07:55 AM
wish of those help There is no way to do it that would work for any Swift class. However, you can do this:
class User: NSObject {
    dynamic var username: String = "admin"
    dynamic var password: String = "123456"
}

let u = User()
u.valueForKey("username") // admin

C# Building Expressions in Linq-to-Entities, Searching all properties' string representations in a type


Tag : chash , By : Robert MacGregor
Date : March 29 2020, 07:55 AM
it fixes the issue I do this without Equals because doesn't in the scope and i will need create some attr or flag to set what prop will be filtered Exactly or Likely, and i just go 1 level in depth of the navigations, so maybe this can help you to understand:
private static readonly MethodInfo ToStringMethod = typeof(object).GetMethod("ToString");
private static readonly MethodInfo StringContainsMethod = typeof(string).GetMethod("Contains");

public static Expression<Func<T, bool>> BuildFilterPredicate<T>(string q)
{
    var query = Expression.Constant(q);
    var type = typeof(T);
    var lambdaParam = Expression.Parameter(type);
    var predicates = type.GetProperties().SelectMany(p => PredicateContainsBuilder(lambdaParam, p, query)).ToList();
    Expression body = predicates[0];
    body = predicates.Skip(1).Aggregate(body, Expression.OrElse);
    return Expression.Lambda<Func<T, bool>>(body, lambdaParam);
}

private static IEnumerable<MethodCallExpression> PredicateContainsBuilder(Expression lambdaParam, PropertyInfo prop, Expression query)
{

    if (prop.PropertyType.IsClass)
        return new List<MethodCallExpression> { Expression.Call(Expression.Call(Expression.Property(lambdaParam, prop), ToStringMethod), StringContainsMethod, query) };

    var properties = prop.PropertyType.GetProperties();
    return properties.Select(p => Expression.Call(Expression.Call(Expression.Property(lambdaParam, p), ToStringMethod), StringContainsMethod, query)).ToList();
}

PHP accessing deeper object properties through string variable


Tag : php , By : Harvey
Date : March 29 2020, 07:55 AM
With these it helps I have this simple function to not get any warnings when a property doesn't exist: , You can explode argument by -> and iterate it. try below solution:
function getProperty($object, $property, $default = ""){

    $properties = explode('->', $property);

    if($properties){
        foreach($properties as $val){
            if(isset($object->$val)){
                $object = $object->$val;
            } else{
                break;
            }
        }
    }

    if (!is_object($object) && $object) return $object;

    return $default;
}

$o = new stdClass();
$o->name = "Peter";

echo $name = getProperty($o, 'name', 'No name'); //output: Peter
echo $email = getProperty($o, 'email', 'No email'); //output: No email

$o = new stdClass();
$o->wife = new stdClass();
$o->wife->name = "Olga";

echo getProperty($o, "wife->name", "No name"); //output: Olga
Related Posts Related QUESTIONS :
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • "The attribute names could not be inferred from bind attribute 'bind-value'" exception in Blazor
  • How to fix ''System.ArgumentException" in c#?
  • C#. Ref returning delegate for ref extension method
  • Swashbuckle Swagger generate an actual guid
  • Trying to make thousands of database calls simultaneously - they stack instead of running concurently
  • run mstest from cmd using testcontainer
  • How to make M:N (many-to-many) relationship where both M and N are the same entities?
  • Consume COM DLL from multiple clients
  • Convert json string response representing UCHAR array to Byte array
  • Why does this LinqPad program produce different results on the second run?
  • ServiceStack how to use MaxLoginAttempts feature
  • What does "late-bound access to the destination object" mean?
  • How to load appsettings.json inside a Static class based on deploy environment so that I can use in other class librarie
  • dynamically add images to view
  • Are static extension methods on User object safe?
  • Process thousands of database calls simultaneously
  • Trying to decrypt a string with public key(not private) using bouncycastle in .net
  • How to retrieve the name of an usb device
  • Query many-to-many related data using Entity Framework Core
  • ASP.NET MVC : how to find the view from a controller?
  • Inconsistent behaviour using Entity Framework for ASP.NET MVC app vs windows service
  • AutoFixture Customize vs Build
  • How to change textbox location at the click of a mouse in live mode?
  • How can I deserialize a XML file without defining the parent node?
  • asp.net core how decrease class coupling
  • ASP.NET Core Razor Pages Routing With parameters
  • String Escaping With $ Interpolation and @ Encoding
  • ConfigurationManager in ASP.NET WebAPI tested with HttpServer
  • Top down shooting in Unity 2D don't work as I want it to
  • Use own redirectUri when the Authentication expires
  • Using "foreach" in string array c#
  • "Object reference not set to an instance of an object" for create multiply models on one view
  • Get data passed trought pushAsync
  • Selector expression dynamic on IQueryable
  • Logut with SignInManager not calling method
  • Exit event handler with MessageBox OK button
  • Can not load view from Custom Renderer Xamarin Forms
  • Looking for a .Net ORM
  • Cost of SortedDictionary.Count
  • All possible combinations of n items selected randomly from a set of x items (algorithm)
  • Displaying process percentage on DOS screen
  • C# Importing Large Volume of Data from CSV to Database
  • c# control location precision
  • Printing to Zebra printer gives faint and blurry images
  • How to avoid stepping into dll code file?
  • Programmaticaly prevent Vista desktop search (WDS) from indexing pst files placed on mapped network drives
  • Is there anyway to reduce IsolatedStorage capacity in Silverlight?
  • C#: How to print a unicode string to console?
  • Frequency Table with Random Values
  • My Visual Studio 2008 web application keeps throwing a .Net error when I first run it, but refreshing fixes it
  • TCP Connection Creation and Closing Event Hooking
  • Find changed properties of a class
  • C#: Object with custom marshaller not containing data after PInvoke call
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com