请教由Type怎样得到一个Instance?

lovexyz 2005-08-15 06:56:52
可能问的不是很明白,解释一下:
比如,我想有一个Create方法,声明成这样了:
object Create(Type t)

现在想问的是:怎样定义这个Create以实现当t不同时返回不同的实例。比如传入t=typeof(xxx)就return 一个XXX的实例

指教
...全文
95 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lovexyz 2005-08-21
  • 打赏
  • 举报
回复
呵呵,感谢各位了
TechEye 2005-08-15
  • 打赏
  • 举报
回复
return Activator.CreateInstance(typeof(typeName), object[] args);
Tony_lau111082 2005-08-15
  • 打赏
  • 举报
回复
try
{
Type myType = typeof(MyClass1);
Type[] types = new Type[1];
types[0] = typeof(int);
// Get the public instance constructor that takes an integer parameter.
ConstructorInfo constructorInfoObj = myType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null,
CallingConventions.HasThis, types, null);
if(constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that is a public " +
"instance method and takes an integer as a parameter is: ");
Console.WriteLine(constructorInfoObj.ToString());
}
else
{
Console.WriteLine("The constructor of MyClass1 that is a public instance " +
"method and takes an integer as a parameter is not available.");
}
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch(ArgumentException e)
{
Console.WriteLine("ArgumentException: " + e.Message);
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException: " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
fengliudai 2005-08-15
  • 打赏
  • 举报
回复
上msdn查了一下,还是猩猩比较牛*
fengliudai 2005-08-15
  • 打赏
  • 举报
回复
同意楼上的,应该自己转变类型
机器人 2005-08-15
  • 打赏
  • 举报
回复
楼主,请使用System.Activator.CreateInstance(Type type)方法。
immonypaggy 2005-08-15
  • 打赏
  • 举报
回复
实际上你是可以ruturn XXX类型的。
只不过你return之后还是object的,在其他地方调用Create(t)的时候,返回的还是object类型,你可以进行转换。
如果要想直接return其他类型,我认为是不行的。你的函数的返回类型已经被你定义成object了,你说是吗?

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧