Get name of property as a string
Using GetMemberInfo from here: Retrieving Property name from lambda expression you can do something like this:
RemoteMgr.ExposeProperty(() => SomeClass.SomeProperty)
public class SomeClass
{
public static string SomeProperty
{
get { return "Foo"; }
}
}
public class RemoteMgr
{
public static void ExposeProperty<T>(Expression<Func<T>> property)
{
var expression = GetMemberInfo(property);
string path = string.Concat(expression.Member.DeclaringType.FullName,
".", expression.Member.Name);
// Do ExposeProperty work here...
}
}
public class Program
{
public static void Main()
{
RemoteMgr.ExposeProperty("SomeSecret", () => SomeClass.SomeProperty);
}
}
Get object property name as a string
Yes you can, with a little change.
function propName(prop, value){
for(var i in prop) {
if (prop[i] == value){
return i;
}
}
return false;
}
Now you can get the value like so:
var pn = propName(person,person.first_name);
// pn = "first_name";
Note I am not sure what it can be used for.
Other Note wont work very well with nested objects. but then again, see the first note.
How do you get a C# property name as a string with reflection?
You can use Expressions to achieve this quite easily. See this blog for a sample.
This makes it so you can create an expression via a lambda, and pull out the name. For example, implementing INotifyPropertyChanged can be reworked to do something like:
public int MyProperty {
get { return myProperty; }
set
{
myProperty = value;
RaisePropertyChanged( () => MyProperty );
}
}
In order to map your equivalent, using the referenced "Reflect" class, you'd do something like:
string propertyName = Reflect.GetProperty(() => SomeProperty).Name;
Viola - property names without magic strings.
Get property name and the type it expects from an object
Use reflection of course.
foreach (PropertyInfo p in typeof(Blog).GetProperties())
{
string propName = p.PropertyType.Name;
Console.WriteLine("Property {0} expects {1} {2}",
p.Name,
"aeiou".Contains(char.ToLower(propName[0])) ? "an" : "a",
propName);
}
Note that GetProperties
also has an overload which accepts a BindingFlags
, which allows you to get only some properties, e.g. instance/static public/private.
Below is an example of how this would theoretically work recursively, though even in this simple example, This creates a StackOverflowException
, because DateTime
has properties which themselves are DateTime
s.
void ListProperties(Type t)
{
foreach (PropertyInfo p in t.GetProperties())
{
string propName = p.PropertyType.Name;
Console.WriteLine("Property {0} expects {1} {2}",
p.Name,
"aeiou".Contains(char.ToLower(propName[0])) ? "an" : "a",
propName);
ListProperties(p.PropertyType);
}
}
ListProperties(typeof(Blog));
how to get a string for a class property name in dart?
import 'dart:mirrors';
class MyClass {
int i, j;
void my_method() { }
int sum() => i + j;
MyClass(this.i, this.j);
static noise() => 42;
static var s;
}
main() {
MyClass myClass = new MyClass(3, 4);
InstanceMirror myClassInstanceMirror = reflect(myClass);
ClassMirror MyClassMirror = myClassInstanceMirror.type;
InstanceMirror res = myClassInstanceMirror.invoke(#sum, []);
print('sum = ${res.reflectee}');
var f = MyClassMirror.invoke(#noise, []);
print('noise = $f');
print('\nMethods:');
Iterable<DeclarationMirror> decls =
MyClassMirror.declarations.values.where(
(dm) => dm is MethodMirror && dm.isRegularMethod);
decls.forEach((MethodMirror mm) {
print(MirrorSystem.getName(mm.simpleName));
});
print('\nAll declarations:');
for (var k in MyClassMirror.declarations.keys) {
print(MirrorSystem.getName(k));
}
MyClassMirror.setField(#s, 91);
print(MyClass.s);
}
the output:
sum = 7
noise = InstanceMirror on 42
Methods:
my_method
sum
noise
All declarations:
i
j
s
my_method
sum
noise
MyClass
91
Get a Swift class's property name as a String
If you are ok with making your properties @objc you can get the property name like so:
class Person {
@objc var firstName: String
var lastName: String
var downloading: Bool
func excludePropertiesFromCloud() -> [String] {
return [#keyPath(firstName)]
}
}
Get string name of property using reflection
If you already have a PropertyInfo
, then @dtb's answer of using PropertyInfo.Name
is the right way. If, however, you're wanting to find out which property's code you're currently in, you'll have to traverse the current call stack to find out which method you're currently executing and derive the property name from there.
var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);
If you don't have a PropertyInfo
object, you can get that from a property expression, like this:
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
To use it, you'd write something like this:
var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"
How to get a property by this name in String?
Unfortunately, you cannot use reflection/mirrors in flutter.
What you can do, which is tedious, is use maps.
class PrefsState {
String a;
const PrefsState({ this.a, });
dynamic getProp(String key) => <String, dynamic>{
'a' : a,
}[key];
}
It's probably better to build the map in the constructor, but if you want const constructors then you'll have to settle for this. Likely won't make much of a difference unless you have a million parameters anyway. Then you use it like so:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test.getProp(key));
I don't think there is a less cumbersome way of doing this, but would love to be proven wrong :-)
Get property name as a string
You can try this:
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);
NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
NSLog(@"Names: %@", propertyNames);
Related Topics
Byte Array to Image Conversion
How to Tell a Lambda Function to Capture a Copy Instead of a Reference in C#
JSON.Net Throws Stackoverflowexception When Using [JSONconvert()]
How to Decompile a .Net Exe into Readable C# Source Code
ASP.NET MVC Custom Error Handling Application_Error Global.Asax
How to Turn a Datatable to a CSV
How to Intercept a Method Call in C#
How to Shut Down the Computer from C#
Serialize Class Containing Dictionary Member
How to Deserialize Xml to Object