Setting Properties In Once Class, Accessing From Another
My question is basically this:
If I set dynamic data from one class, can I access that same data from another class? Below is the rough pseudocode of what I am trying to do:
Public Class Person
{
public string ID { get; set; }
public string Name { get; set; }
}
And, I do the below:
Public Class SomeClass
{
private void SomeMethod()
{
List<Person> p = new List<Person>();
loop {
p.Add(id[i], name[i]);
Timer t = new Timer();
t.Interval = 1000;
}
}
Can 开发者_JAVA技巧I access the values set in SomeClass from SomeOtherClass such that:
Public SomeOtherClass
{
private List<Person> SomeOtherMethod(string id)
{
// HERE, THE RESPONSE VALUES MAY CHANGE BASED ON
// WHERE IN THE LOOP SomeClass.SomeMethod HAS SET
// THE VALUES IN Person.
var query = from p in Person
where p.ID == id
select p;
return query.ToList();
}
}
Thanks for your thoughts...
You can access the members (ID, Name) for those properties, since you declared them as public.
When you say "Person", you're referring to a Type - the Person type.
In order to access a member of a specific Person, you need to use an instance of Person.
Person thePersonInstance = new Person(5, "Joe");
thePersonInstance.ID = 3; // This is fine, since it's public
However, in your example, you would need to provide a specific collection of "Person" instances to your method in SomeOtherClass. Something like:
Public SomeOtherClass
{
// You need to provide some collection of Person instances!
public List<Person> SomeOtherMethod(string id, IEnumerable<Person> people)
{
var query = from p in people
where p.ID == id
select p;
return query.ToList();
}
}
You could then use this somewhere else, like:
void SomeMethod()
{
List<Person> people = new List<Person>();
people.Add(new Person(1, "Name1");
people.Add(new Person(2, "Name2");
SomeOtherClass other = new SomeOtherClass();
List<Person> filteredPeople = other.SomeOtherMethod(1);
}
精彩评论