473,545 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

instantiate a class using reflection issue

Hi how can I instaltiate a class and call its method. the class has
non default constructor. all examples i see only with class of defatul
constructor. I am trying to pull the unit test out from the product
source code, but still want to execute them under nunit.

I am trying this idea on nunit sample source code. Here is my class
and the experiemental code: both money.cs and Imoney.cs is compiled to
cs_money.dll. then I create another console app that include
cs_money.dll and try to instantiate the money class at runtime. (code
in moneytestwithre flection.cs; the driver is program.cs.). I can see
the disassembler able to see the all the methods and constructor, so i
think i can use refelction to do the same thing. //excepton already
thrown here saying can;t find the constructor when I call
createinstance in TRYITOUT.CS. I have include all the source file
here.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Money.cs:
namespace NUnitApp.Sample s.BigMoney
{

using System;
using System.Text;

/// <summary>A simple Money.</summary>
class Money: IMoney {

private int fAmount;
private String fCurrency;

/// <summary>Constr ucts a money from the given amount and
/// currency.</summary>
public Money(int amount, String currency) {
fAmount= amount;
fCurrency= currency;
}

/// <summary>Adds a money to this money. Forwards the request to
/// the AddMoney helper.</summary>
public IMoney Add(IMoney m) {
return m.AddMoney(this );
}

public IMoney AddMoney(Money m) {
if (m.Currency.Equ als(Currency) )
return new Money(Amount+m. Amount, Currency);
return new MoneyBag(this, m);
}

public IMoney AddMoneyBag(Mon eyBag s) {
return s.AddMoney(this );
}

public int Amount {
get { return fAmount; }
}

public String Currency {
get { return fCurrency; }
}

public override bool Equals(Object anObject) {
if (IsZero)
if (anObject is IMoney)
return ((IMoney)anObje ct).IsZero;
if (anObject is Money) {
Money aMoney= (Money)anObject ;
return aMoney.Currency .Equals(Currenc y)
&& Amount == aMoney.Amount;
}
return false;
}

public override int GetHashCode() {
return fCurrency.GetHa shCode()+fAmoun t;
}

public bool IsZero {
get { return Amount == 0; }
}

public IMoney Multiply(int factor) {
return new Money(Amount*fa ctor, Currency);
}

public IMoney Negate() {
return new Money(-Amount, Currency);
}

public IMoney Subtract(IMoney m) {
return Add(m.Negate()) ;
}

public override String ToString() {
StringBuilder buffer = new StringBuilder() ;
buffer.Append("["+Amount+" "+Currency+ "]");
return buffer.ToString ();
}
}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IMoney.cs:
namespace NUnitApp.Sample s.BigMoney
{

/// <summary>The common interface for simple Monies and MoneyBags.</
summary>
interface IMoney {

/// <summary>Adds a money to this money.</summary>
IMoney Add(IMoney m);

/// <summary>Adds a simple Money to this money. This is a helper
method for
/// implementing double dispatch.</summary>
IMoney AddMoney(Money m);

/// <summary>Adds a MoneyBag to this money. This is a helper
method for
/// implementing double dispatch.</summary>
IMoney AddMoneyBag(Mon eyBag s);

/// <value>True if this money is zero.</value>
bool IsZero { get; }

/// <summary>Multip lies a money by the given factor.</summary>
IMoney Multiply(int factor);

/// <summary>Negate s this money.</summary>
IMoney Negate();

/// <summary>Subtra cts a money from this money.</summary>
IMoney Subtract(IMoney m);
}
}

MY TEst code:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TRYITOUT.CS

using System;
//using System.Collecti ons.Generic;
//using System.Text;
using System.Reflecti on;
using NUnit.Framework ;

namespace cs_money_test_b lar
{
public class MoneyBagTestWit hReflection
{
//Money
private Object f12CHF;
private Object f14CHF;
private Object f7USD;
private Object f21USD;
//MoneyBag
private Object fMB1;
private Object fMB2;

//[SetUp]
public void SetUP()
{
//jsut assume the dll is present for now
System.Reflecti on.Assembly assem =
System.Reflecti on.Assembly.Loa dFrom(@"C:\test framework
\nunit\source\s amples\csharp\m oney\bin\Debug\ cs-money.dll");
//Create Type
System.Type typef14CHF =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y",true);
//Type typeinfo = typeof(typef14C HF);
BindingFlags flags = BindingFlags.In stance |
BindingFlags.Pu blic | BindingFlags.No nPublic |
BindingFlags.Cr eateInstance;
//Console.WriteLi ne("typefull name :{0} Constructors: {1},
another {2}",typeinfo,
typeinfo.GetCon structors(Flags Attribute).leng th,
ConstructorInfo[] myctor = typef14CHF.GetC onstructors();
//Console.WriteLi ne("cotor {0}, {1}", myctor[0],
myctor[1]);
object [] arg = new object[2];
arg[0] = 12;
arg[1] = "CHF";

f14CHF =
System.Activato r.CreateInstanc e(typef14CHF,fa lse,flags,null, arg,null,null);
System.Type typef12CHF =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y",true);
//excepton already thrown here saying can;t find the constructor.
//f12CHF = System.Activato r.CreateInstanc e(typef12CHF(12 ,
"CHF"));
System.Type typef7USD =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y",true);
//f7USD = System.Activato r.CreateInstanc e(typef7USD(7,
"USD"));
System.Type typef21USD =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y", true);
//f21USD =
System.Activato r.CreateInstanc e(typef21USD(21 ,"USd"));
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EntryPoint.cs:
using System;
using cs_money_test_b lar;

namespace EntryDriver
{
class Program
{
static void Main(string[] args)
{
MoneyBagTestWit hReflection myreflection = new
MoneyBagTestWit hReflection();
myreflection.Se tUP();
}
}
}

Jul 7 '07 #1
1 2830
learning wrote:
Hi how can I instaltiate a class and call its method. the class has
non default constructor. all examples i see only with class of defatul
constructor. I am trying to pull the unit test out from the product
source code, but still want to execute them under nunit.

I am trying this idea on nunit sample source code. Here is my class
and the experiemental code: both money.cs and Imoney.cs is compiled to
cs_money.dll. then I create another console app that include
cs_money.dll and try to instantiate the money class at runtime. (code
in moneytestwithre flection.cs; the driver is program.cs.). I can see
the disassembler able to see the all the methods and constructor, so i
think i can use refelction to do the same thing. //excepton already
thrown here saying can;t find the constructor when I call
createinstance in TRYITOUT.CS. I have include all the source file
here.
Money.cs:
class Money: IMoney {
public Money(int amount, String currency) {
TRYITOUT.CS
System.Reflecti on.Assembly assem =
System.Reflecti on.Assembly.Loa dFrom(@"C:\test framework
\nunit\source\s amples\csharp\m oney\bin\Debug\ cs-money.dll");
System.Type typef14CHF =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y",true);
BindingFlags flags = BindingFlags.In stance |
BindingFlags.Pu blic | BindingFlags.No nPublic |
BindingFlags.Cr eateInstance;
object [] arg = new object[2];
arg[0] = 12;
arg[1] = "CHF";

f14CHF =
System.Activato r.CreateInstanc e(typef14CHF,fa lse,flags,null, arg,null,null);
System.Type typef12CHF =
assem.GetType(" NUnitApp.Sample s.BigMoney.Mone y",true);
Three questions:
1) Why is Monet class not public ?
2) Why not use Assembly CreateInstance ?
3) Why do you specify the name of the interface instead of the
name of the class you want to interface ?

Arne
Jul 7 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
8422
by: samlee | last post by:
Hi All, I'm learning how to write C# using reflection, but don't know how to code using reflection this.Controls.Add(this.label1); Could anyone help, Thank in advance. xxx======================================================================
3
5070
by: J E E | last post by:
Hi! Is it possible to access fields in a derived class using reflection? Code below works fine when I access it as a private member in the Page class, but not when accessing base class member through an interface reference. I have tried to change the snd argement to SetAttribute method from 'Name', 'set_Name' to '_name'. That doesn't...
2
2370
by: Cezar | last post by:
Hi, Does anyone know how to get the list of local declared method of a class using Reflection. I didn't see a flag like %IsLocal% for MethodInfo... The code I use now returns all method, locally declared and inherited <snip> MethodInfo methodsInfo = cl.GetMethods();
5
19863
by: zfeld | last post by:
How do I cast an object to its proper class at runtime given its System.Type I have code that looks like this: MyObject class has subclasses of MySubObjectA & MySubObjectB: MyObject obja = new MySubObjectA (); MyObject objb = new MySubObjectB (); ArrayList list = new ArrayList();
8
16866
by: Robert W. | last post by:
I've almost completed building a Model-View-Controller but have run into a snag. When an event is fired on a form control I want to automatically updated the "connnected" property in the Model. This works fine if all of the properties are at the top (root level) of the model but I'd like to keep them in nested classes to organize them...
6
1194
by: ECathell | last post by:
I have a routine that compares 2 intances of the same object to see if there are any changes. The problem is that even though there are no changes, it tells me there are. I have even tried running a new routine that shows a messagebox with both objects' property values. below is my code. this is the actual comparison code: Dim Properties()...
3
4075
by: Steve Amey | last post by:
Hi all I am using reflection to read the values of properties from a class. The class is returned from a Web Service so I have to access the class using FieldInfo (Using VS 2003 which converts the Properties into Fields when it comes out of the Web Service). I have this at the moment: Private _aDataSource As Object 'Person class
1
1490
by: sk.rasheedfarhan | last post by:
Hi , I am using C# I am having 4 classes. like below. public class A { String m_strRuleName; String m_strRuleGuid; // Some member functions. public Object NextItem; }
4
6804
by: =?Utf-8?B?QWJoaQ==?= | last post by:
I am using Reflection to invoke methods dynamically. I have got a special requirement where I need to pass a value to method by setting the custom method attribute. As I cannot change the signature of method to pass a new parameter, I am setting the custom attribute of a given method and then accessing the attribute from method. Since...
0
7499
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
1
7456
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6022
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5359
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3490
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1919
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1044
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
743
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.