如何动态更改对象的名称? [英] How to change the name of an object dynamically?

查看:56
本文介绍了如何动态更改对象的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,



下面是我想要实现的伪代码:





函数(字符串名称)

{



计时器 t +名称 =新定时器();

(t +名称)。开始();



}





我的参数名称名称将会改变。根据参数的名称,我将创建一个

对象并使用它。



总之我想动态更改名称对象并使用它的属性。







我试过了:

反思:但是在这里我们只能得到一个没有设置它们的对象的属性。



使用的对象类:我使用了对象类,做了类型转换,但最终你将不得不改变对象的名称....所以无法实现它。







请建议,



谢谢和问候,

Rahul

解决方案

如果它在代码中用于访问对象引用的对象的名称,然后您可以使用 Dictionary< string,object> 来关联自定义,运行时,名称对象引用,基本上获得相同的效果。


下面我已经声明了MyTimer类,并且在它的构造函数中我已经完成了下面的一些事情:

自定义计时器的排序:



定时器t; 
字符串名称;
public MyTimer( string name)
{
Name = name ;
t = new Timer();

}

public void StartTimer(< span class =code-keyword> int interval)
{
mydictionary.Add(t,t.GetHashCode());
t.Interval = interval;
t.Elapsed + = new ElapsedEventHandler(MyTimer_Elapsed);
t.Enabled = true ;
t.Start();
}

public void MyTimer_Elapsed( object sender,ElapsedEventArgs e)
{

t.AutoReset = false ;
t.Enabled = false ;
t.Stop();
}

}



}



}


Hello friends,

Below is a pseudo code which i want to realize:


function(string name)
{

Timer t+name = new Timer();
(t+name).Start();

}


My parameter name name will change. Depending upon the name of the parameter i will create an
object and use it.

In short i want to dynamically change the name of the object and use its properties.



I tried out:
Reflection : But in this we can only get the properties of an object not set them.

Used Object Class: I used object class, did typecasting, but eventually you will have to change the name of the object.... so couldnt achieve it.



Please advice,

Thanks and Regards,
Rahul

解决方案

If the name of the object it is just used in your code to access the object reference, then you could use a Dictionary<string, object> for associate a custom, runtime, name to the object reference, obtaining, basically, the same effect.


Below i have declared MyTimer class and in its constructor i have done some thing like below:
Sort of a customized timer:

Timer t;
               String Name;
    public MyTimer(string name)
    {
        Name = name;
        t = new Timer();

    }

    public void StartTimer(int interval)
    {
        mydictionary.Add(t,t.GetHashCode());
        t.Interval = interval;
        t.Elapsed += new ElapsedEventHandler(MyTimer_Elapsed);
        t.Enabled = true;
        t.Start();
    }

    public void MyTimer_Elapsed(object sender, ElapsedEventArgs e)
    {

        t.AutoReset = false;
        t.Enabled = false;
        t.Stop();
    }

 }


}

}


这篇关于如何动态更改对象的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆