Reputation: 5409
Example
public class MyItems
{
public object Test1 {get ; set; }
public object Test2 {get ; set; }
public object Test3 {get ; set; }
public object Test4 {get ; set; }
public List<object> itemList
{
get
{
return new List<object>
{
Test1,Test2,Test3,Test4
}
}
}
}
public void LoadItems()
{
foreach (var item in MyItems.itemList)
{
//get name of item here (asin, Test1, Test2)
}
}
**
I have tried this with reflection.. asin typeof(MyItems).GetFields()
etc.. but that doesn't work.
How can I find out which name "item" has? Test1? Test2?? etc...
Upvotes: 2
Views: 296
Reputation: 223207
var test = typeof(MyItems).GetProperties().Select(c=>c.Name);
The above will give you an Enumerable of properties name. if you want to get the name of the properties in the list use:
var test = typeof(MyItems).GetProperties().Select(c=>c.Name).ToList();
EDIT:
From your comment, may be you are looking for :
foreach (var item in m.itemList)
{
var test2 = (item.GetType()).GetProperties().Select(c => c.Name);
}
Upvotes: 2
Reputation: 8359
You can access the name of properties with this code (see MSDN)
Type myType =(typeof(MyTypeClass));
// Get the public properties.
PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public|BindingFlags.Instance);
for(int i=0;i<myPropertyInfo.Length;i++)
{
PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i];
Console.WriteLine("The property name is {0}.", myPropInfo.Name);
Console.WriteLine("The property type is {0}.", myPropInfo.PropertyType);
}
But right now I don't know any code to access the name of a reference!
Upvotes: 0
Reputation: 30882
The "name" of the object is neither "Test1"
, nor "MyItems[0]"
.
Both those are just references to the object, that is in effect, nameless.
I do not know of any technique in C# that could give you all the references to an object, given an object, so I do not think what you want is possible, the way you want it.
Upvotes: 1