Passing an object as a parameter in a method
I am working on a C# project. I have a Nameclass class with some properties(first name, lastname). In dept class I have instatiated the Nameclass and assigned some values to firstname and lastname. Now开发者_Go百科 in dept class I am calling another method setValues() which belongs to Order class. In this method I am passing this NameClass and some other vlaues. The code looks like this.
Order.setValues(nameObject, address, city, state,zip)
Now in Order Class when when I am trying to access the properties from nameObject Its not showing any properits. Why I am not getting the firstname and last name values here in Order class. Do I have to instantiate the NameClass again in Order class inorder to get the properties. I appreciate if you can tell me what mistake I am doing here.
You're not showing your code, but there are a few possibilities, including:
- Make sure that your
setValues
method is passing the first parameter using the proper type, ie:void setValues(NameClass name, string address, ...
, and not usingvoid setValues(object name, ...
. - Make sure that the properties or fields in
NameClass
(firstname
andlastname
) are not markedprivate
, but are insteadpublic
(orinternal
if you're in the same project).
I assume the reason this is happening is because your Order.setValues()
method has the following signature:
public static void setValues(object nameObject, string address, string city, string state, string zip)
If my estimation is correct then the answer is simple. Your object is being treated as an type object rather than as type NameClass
. You can't know at compile-time what properties are inside a base class object short of Reflextion.
Solution would be to simply change the type of nameObject parameter in your method to type NameClass
... all this is assuming my assumption is correct.
You've either declared the parameter as type object, or the data members are not public. In the former case, there's no way for VC# to know what members are in your object.
精彩评论