I tried to use the code PropertyInfo[] but the code is not getting any attribute. Because the attribute inside class1 is just a reference variable
public readonly subClass1 sClass1;
public readonly subClass2 sClass2;
public readonly subClass3 sClass3;
public class1()//constructor
{
sClass1= new subClass1();
sbClass2= new subClass2();
sClass3= new subClass3();
}
My problem is, i can't access those 3 classes just by using PropertyInfo[]
but my i can access it using
Type type = typeof(class1);
FieldInfo[] fields = type.GetFields();
var i = 0;
foreach (var field in fields)
{
var f = field.GetType().GetFields();
i++;
}
But this code is not working as i want to work, they can get the class but i can't get the property of every subClass
What i want is something like this
var f = class1.sClass1;
my variable f will now hold the every property of a class.
I'm sorry if i can't explain it well. If you want to ask something, just comment below
by the way this is the inside code of every subClass
public string X{ get; set; }
public string Y{ get; set; }
public string Width { get; set; }
public string Length { get; set; }
You will have to do it recursively
void GetFields(Type type)
{
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance
| BindingFlags.Public | BindingFlags.NonPublic)) {
Console.WriteLine("{0} {1}", fieldInfo.FieldType.Name, fieldInfo.Name);
if (fieldInfo.FieldType.IsClass)
GetFields(fieldInfo.FieldType);
}
You have to use field.FieldType instead of using field.GetType()
Related
I want to use GetProperties to get the properties from the parent class via the child and, despite researching this, have been unsuccessful.
I tried the next without any result:
PropertyInfo[] fields = t.GetProperties();
PropertyInfo[] fields1 = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
PropertyInfo[] propNames = t.BaseType.GetProperties( BindingFlags.Public | BindingFlags.Instance);
Just got it the properties from the child class, but dont get the properties from the parent.
Classes
public class A: B
{
public string a1 { get; set; }
public string a2 { get; set; }
public string a3 { get; set; }
public string a4 { get; set; }
}
public class B
{
public string b1;
}
Using this code I am getting A's properties but not the property in B.
Does this code work? Do I need to configure something in some place?
In your declaration
public class B
{
public string b1;
}
b1 is a field, not a property. You should either
Use GetFields():
FieldInfo[] fields = t.GetFields();
which will get the fields (as expected) - note that the documentation says that
Generally, you should use fields only for variables that have private or protected accessibility.
Make b1 a property, e.g. by adding { get; set; } accessors to it.
I'm trying to dynamically get all the values of a specific property from all class instances. I've managed to do it with one property
public class fighter
{
public string Name { get; set; }
public double Height { get; set; }
}
fighter[] roster[5] = new fighter();
string namearray = roster.Select(x => x.Name).ToArray();
int weightarray = roster.Select(x => x.Weight).ToArray();
However I want to reference the property with a variable and put it in a loop so I don't need a select function for every property. Is there anyway to do this, or any other method to get all values of a property from all objects where this could work?
class Program
{
static void Main(string[] args)
{
stud stud = new stud() { id=10,name="test" };
PropertyInfo[] propertyInfo;
propertyInfo = typeof(stud).GetProperties(BindingFlags.Public|BindingFlags.Instance);
foreach (var item in propertyInfo)
{
Console.WriteLine(item.Name + " : " + item.GetValue(stud));
}
Console.ReadLine();
}
}
public class stud {
public int id { get; set; }
public string name { get; set; }
}
use following code, i have created a propertyInfo class from System.Reflection namespace which allows to get property names of the class. after which once you get all the names of properties can be accessed using propertyinfo.GetValue function.
I have a little problem, below my code:
public class A
{
public string ObjectA { get; set; }
}
public void Run()
{
A a = new A();
a.ObjectA = "Test number 1";
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
PropertyInfo myPropertyInfo = a.GetType().GetProperty("ObjectA", flags);
object myNewObject = myPropertyInfo.GetValue(a);// Here should be reference
a.ObjectA = "Test number 2";//After this line value myNewObject continued "Test number 1"
}
So my value myNewObject must be in output "Test number 2". Is there any way? It is this at all possible?
Wrong!
You're getting the string rather than the instance of A using reflection.
Changing A.ObjectA doesn't change the string reference. Actually, you're setting a different string to the backing string class field by the ObjectA property...
Auto-properties are syntactic sugar to avoid explicitly declaring class fields to properties which perform nothing when getting or setting their values:
// For example:
public string Text { get; set; }
// is...
private string _text;
public string Text { get { return _text; } set { _text = value; } }
Now turn your code into regular one (no reflection):
A a = new A();
a.ObjectA = "hello world";
object myNewObject = a.ObjectA;
// Do you think now that myNewObject should change...? :)
a.ObjectA = "goodbye";
Is there any way? It is this at all possible?
No.
Maybe you can simulate this behavior using a Func<T>...
Func<object> myNewObjectGetter = () => myPropertyInfo.GetValue(a);
Now, whenever you call myNewObjectGetter() you're going to get the most fresh value of the whole property. BTW, this still doesn't address the impossible!
Is there any way?
No. You can't put a reference to a property into an object variable. Such a variable can only hold a normal value, such as the string you put into it.
That answers the question as asked. You can clarify what you want to achieve and maybe we can suggest a better way.
Probably there is no solution but I show some code
public class MyRows
{
public string Key { get; set; }
public int Id { get; set; }
public object Val { get; set; }
}
public abstract class BasicDTO
{
public int? Id { get; private set; }
public PropertyInfo[] PropertyDTO;
protected Type myType;
public BasicDTO()
{
Load();
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
PropertyDTO = myType.GetProperties(flags);
}
}
public class CustomerDTO : BasicDTO
{
public string Surname { get; set; }
public string Phone { get; set; }
public CustomerDTO() { }
protected override void Load()
{
myType = typeof(CustomerDTO);
}
}
Now my basic method
public void Run(BasicDTO dto)
{
PropertyInfo pi = dto.PropertyDTO.Where(x => x.Name == "Surname").SingleOrDefault();
MyRows mr = new MyRows();
mr.Val = pi.GetValue(dto);//Here I need reference
}
When I change CustomerDTO.Surname my value mr.Val it must also be changed.
As I wrote above, it is probably impossible, but maybe anybody have a idea.
BTW: Value mr.Val I use only for binding (WPF). So maybe you have any other suggestions, how solve problem. I will be grateful for your help
Take this class for example:
public class Applicant : UniClass<Applicant>
{
[Key]
public int Id { get; set; }
[Field("X.838.APP.SSN")]
public string SSN { get; set; }
[Field("APP.SORT.LAST.NAME")]
public string FirstName { get; set; }
[Field("APP.SORT.FIRST.NAME")]
public string LastName { get; set; }
[Field("X.838.APP.MOST.RECENT.APPL")]
public int MostRecentApplicationId { get; set; }
}
How would I go about getting all of the properties that are decorated with the field attribute, get their types, and then assign a value to them?
This is all done with reflection. Once you have a Type object, you can then get its PropertyInfo with myType.GetProperties(), from there, you can get each property's attributes with GetCustomAttributes(), and from there if you find your attribute, you've got a winner, and then you can proceed to work with it as you please.
You already have the PropertyInfo object, so you can assign to it with PropertyInfo.SetValue(object target, object value, object[] index)
You'll need to use Reflection:
var props =
from prop in typeof(Applicant).GetProperties()
select new {
Property = prop,
Attrs = prop.GetCustomAttributes(typeof(FieldAttribute), false).Cast<FieldAttribute>()
} into propAndAttr
where propAndAttr.Attrs.Any()
select propAndAttr;
You can then iterate through this query to set the values:
foreach (var prop in props) {
var propType = prop.Property.PropertyType;
var valueToSet = GetAValueToSet(); // here's where you do whatever you need to do to determine the value that gets set
prop.Property.SetValue(applicantInstance, valueToSet, null);
}
You would just need to invoke the appropriate reflection methods - try this:
<MyApplicationInstance>.GetType().GetProperties().Where(x => x.GetCustomAttributes().Where(y => (y as FieldAttribute) != null).Count() > 0);
I am trying to retrieve the public properties of an object but it is returning nothing. Can you tell me what I'm doing wrong.
public class AdHocCallReportViewModel : ReportViewModel
{
public string OperatorForCustEquipID { get; set; }
public string OperatorForPriorityID { get; set; }
public string OperatorForCallTypeID { get; set; }
public string OperatorForStatusID { get; set; }
}
public UpdateReportParameters(AdHocCallReportViewModel rvm)
{
var type = rvm.GetType();
foreach (var f in type.GetFields().Where(f => f.IsPublic))
{
Console.WriteLine(f.Name);
Console.WriteLine(f.GetValue(rvm).ToString());
}
}
When stepping through the code, it skips over the foreach loop because GetFields returns zero items.
You haven't got public fields. They are properties. So try type.GetProperties() instead.
You are trying to get fields, you should try to call GetProperties()
Pass BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public to get all instance fields.
On second thought, I'm seeing that you are explicitly filtering for public fields. The class does not have any public fields. The fields that are automatically generated by the compiler as the backing store for the properties are private.