Create object of Interface thru Reflection

S

sippyuconn

Hi

Creating an Control Thru Refelection that also has an Interface on it
I can create the Control but when I try to get an Instance of Interface get
exception that cannot

Unable to cast object of type 'UserControls.UserControl2' to type
'UserControls.ISettings'.


Any ideas why ???

Thanks


UserControl
=========
namespace UserControls
{
public partial class UserControl2 : UserControl, ISettings
{
public event EventHandler OnSettingsModified;
}
}

Reflection to get to Interface
====================

foreach (Type type in asm.GetTypes())
{
if (type.IsClass == true )
{
bClass = false;
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.FullName.Contains("ISettings"))
{
bClass = true;
break;
}
}

if(bClass)
{


Control control = Activator.CreateInstance(type)
as Control;

try
{

object obj = Activator.CreateInstance(type)
as object;

((ISettings)obj).OnSettingsModified += new
EventHandler(Configuration_OnValid);

}
catch() {}
 
S

sloan

You can alter you code slightly to


((ISettings)obj).OnSettingsModified += new
EventHandler(Configuration_OnValid);



ISettings settings = obj as ISettings;
if (null!=settings)
{

//wire up the event here

}
else
{
if (null!=obj)
{
Console.Writeline ( obj.GetType().ToString();
}
}

Something like that.


I have a reflection based Interface example here:
http://sholliday.spaces.live.com/Blog/cns!A68482B9628A842A!126.entry
that you can download. To compare your code against I guess.
 
S

sloan

Yeah, I agree.

ISettings could be coming from anywhere based on the string compare.

The code I had would at least get you to the "Oh...that's what that thing
really is"............

Even if you have two ISettings with the EXACT same implementation........if
they're in different assemblies or different namespaces......they're
different.

You'd have to do even more reflecting with GetValue SetValue CanWrite
reflection stuff. :<
 
C

Colbert Zhou [MSFT]

Hello Sippyuconn,

I have added some parts to finish your codes. It works fine in my side. The
following is the whole version,

namespace WindowsFormsApplication
{
public interface ISettings
{
event EventHandler OnSettingsModified;
}

public partial class UserControl2 : UserControl, ISettings
{
public UserControl2()
{
InitializeComponent();
}

#region ISettings Members

public event EventHandler OnSettingsModified;

#endregion
}
}

private void Form1_Load(object sender, EventArgs e)
{
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.IsClass == true)
{
bool bClass = false;
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.FullName.Contains("ISettings"))
{
bClass = true;
break;
}
}

if (bClass)
{
Control control = Activator.CreateInstance(type) as Control;
try
{
object obj = Activator.CreateInstance(type) as object;
((ISettings)obj).OnSettingsModified += new
EventHandler(Form1_OnSettingsModified);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}

So Peter's suggestion hits the most likely possibility, in my opinion. If
you can debug the codes, please set a breakpoint at the try block beginning
line,

If the type is the right class implements the ISettings interface showed in
our codes. We can see type variable in Locals window as,
{Name = "UserControl2" FullName = "WindowsFormsApplication.UserControl2"}

So please have a check if there is any other interfaces defined in our
assembly that also contains the string "ISettings". Please let us to know
if this helps. We are looking forward to your detailed information.

Have a nice day to all!

Best regards,
Colbert Zhou ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/default.aspx?target=assistance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
C

Colbert Zhou [MSFT]

Hello,

I am writing to check the status of the issue on your side. Could you
please let me know if the suggestion works for you or not?

Have a great day!

Best regards,
Colbert Zhou ([email protected], remove 'online.')
Microsoft Online Community Support

=================================================
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

This posting is provided "AS IS" with no warranties, and confers no rights.
=================================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top