开发者

c# get attributes from object

I'm a bit new to C# and I got this script that gets a record from a mssql database. There it converts the key to an object.

Its:

Object obj = result[i];

When I enable a breakpoint on the line after the declaration I see the data that is inside the object. Now I need to access the attribute with the data but because Im a bit new to C# I dont know how to do that.

Lets say the attribute is called: name I made a new class of my own also with the attribute name.

When I try to get the name of the key to my object with:

myObject.Name = (string) obj.Name;

The IDE already gives a开发者_Go百科n error that the attribute in the obj isnt available.

How can I access the name attribute of the object to get it to my own object?

Thanks!


So result[i] is an instance of your class (which I'll call Foo for convenience)? Then you can say

Foo obj = result[i];
myObject.Name = obj.Name;

or

Object obj = result[i];
myObject.Name = ((Foo)obj).Name;


You need to cast your object to proper type. E.g. if your object is:

class MyObject
{
    public string Name { get; set; }
}

than you need to cast it like:

MyObject obj = (MyObject)result[i];


you're trying to access an attribute of the Object class, and it has no attributes. You either have to cast your obj to the class that you created, the one that has the Name attribute, or (more simply), when reading the database read it directly into an instance of your class, something like:

MyClass obj = result[i]


What data is present in result[i]? Is it just a string from a field in the record in the database? (That is, is result a DataRow?) As it stands, you're placing it inside of just an Object which doesn't know much about it. Basically, you're "boxing" it and removing knowledge of the object's data from the compiler.

If result[i] is just a string, try something like:

myObject.Name = System.Convert.ToString(result[i]);

Now, this is fairly beginner in that there are other considerations to be made here. If result[i] is ever null then this will throw an exception, etc. But while you're learning this should get the data you're looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜