473,508 Members | 2,356 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 moneytestwithreflection.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.Samples.BigMoney
{

using System;
using System.Text;

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

private int fAmount;
private String fCurrency;

/// <summary>Constructs 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.Equals(Currency) )
return new Money(Amount+m.Amount, Currency);
return new MoneyBag(this, m);
}

public IMoney AddMoneyBag(MoneyBag 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)anObject).IsZero;
if (anObject is Money) {
Money aMoney= (Money)anObject;
return aMoney.Currency.Equals(Currency)
&& Amount == aMoney.Amount;
}
return false;
}

public override int GetHashCode() {
return fCurrency.GetHashCode()+fAmount;
}

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

public IMoney Multiply(int factor) {
return new Money(Amount*factor, 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.Samples.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(MoneyBag s);

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

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

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

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

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

using System;
//using System.Collections.Generic;
//using System.Text;
using System.Reflection;
using NUnit.Framework;

namespace cs_money_test_blar
{
public class MoneyBagTestWithReflection
{
//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.Reflection.Assembly assem =
System.Reflection.Assembly.LoadFrom(@"C:\testframe work
\nunit\source\samples\csharp\money\bin\Debug\cs-money.dll");
//Create Type
System.Type typef14CHF =
assem.GetType("NUnitApp.Samples.BigMoney.Money",tr ue);
//Type typeinfo = typeof(typef14CHF);
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.CreateInstance;
//Console.WriteLine("typefull name :{0} Constructors: {1},
another {2}",typeinfo,
typeinfo.GetConstructors(FlagsAttribute).length,
ConstructorInfo[] myctor = typef14CHF.GetConstructors();
//Console.WriteLine("cotor {0}, {1}", myctor[0],
myctor[1]);
object [] arg = new object[2];
arg[0] = 12;
arg[1] = "CHF";

f14CHF =
System.Activator.CreateInstance(typef14CHF,false,f lags,null,arg,null,null);
System.Type typef12CHF =
assem.GetType("NUnitApp.Samples.BigMoney.Money",tr ue);
//excepton already thrown here saying can;t find the constructor.
//f12CHF = System.Activator.CreateInstance(typef12CHF(12,
"CHF"));
System.Type typef7USD =
assem.GetType("NUnitApp.Samples.BigMoney.Money",tr ue);
//f7USD = System.Activator.CreateInstance(typef7USD(7,
"USD"));
System.Type typef21USD =
assem.GetType("NUnitApp.Samples.BigMoney.Money", true);
//f21USD =
System.Activator.CreateInstance(typef21USD(21,"USd "));
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EntryPoint.cs:
using System;
using cs_money_test_blar;

namespace EntryDriver
{
class Program
{
static void Main(string[] args)
{
MoneyBagTestWithReflection myreflection = new
MoneyBagTestWithReflection();
myreflection.SetUP();
}
}
}

Jul 7 '07 #1
1 2826
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 moneytestwithreflection.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.Reflection.Assembly assem =
System.Reflection.Assembly.LoadFrom(@"C:\testframe work
\nunit\source\samples\csharp\money\bin\Debug\cs-money.dll");
System.Type typef14CHF =
assem.GetType("NUnitApp.Samples.BigMoney.Money",tr ue);
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.CreateInstance;
object [] arg = new object[2];
arg[0] = 12;
arg[1] = "CHF";

f14CHF =
System.Activator.CreateInstance(typef14CHF,false,f lags,null,arg,null,null);
System.Type typef12CHF =
assem.GetType("NUnitApp.Samples.BigMoney.Money",tr ue);
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
8416
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. ...
3
5069
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...
2
2365
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,...
5
19840
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 =...
8
16854
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. ...
6
1191
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...
3
4069
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...
1
1487
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...
0
7115
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7377
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7036
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...
0
7489
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5624
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,...
0
4705
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3191
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...
0
1547
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 ...
0
414
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...

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.