C# 使用 GetType() 进行转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/555462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast with GetType()
提问by
Is it possible to cast an object to the type returned from GetType()
? I'd like a generic method that can accept an object (for anonymous types) but then return an object cast as the anonymous type. I've been thinking of using the LCG DynamicMethod to build a method on a container class, but I can't exactly figure out what that would look like. The idea to cast with the GetType()
method was to be able to get the anonymous type and cast an object to its actual type without actually knowing the type.
是否可以将对象强制转换为从 返回的类型GetType()
?我想要一个通用方法,它可以接受一个对象(对于匿名类型),然后返回一个转换为匿名类型的对象。我一直在考虑使用 LCG DynamicMethod 在容器类上构建一个方法,但我无法完全弄清楚它会是什么样子。使用该GetType()
方法进行强制转换的想法是能够获取匿名类型并将对象强制转换为其实际类型,而无需实际了解该类型。
The overarching goal is to stick anonymous-typed objects into a container, that I could then share and pass between methods.
总体目标是将匿名类型的对象粘贴到容器中,然后我可以在方法之间共享和传递。
采纳答案by Marc Gravell
Your intent is very unclear; however, one option is generics and MakeGenericMethod
in particular. What do you want to do with this? For example:
你的意图很不清楚;然而,一种选择是泛型MakeGenericMethod
,特别是。你想用这个做什么?例如:
static class Program
{
static void Main()
{
object obj = 123.45;
typeof(Program).GetMethod("DoSomething")
.MakeGenericMethod(obj.GetType())
.Invoke(null, new object[] { obj });
}
public static void DoSomething<T>(T value)
{
T item = value; // well... now what?
}
}
So now we have the value, typed as double
via generics - but there still isn't much we can do with it except for calling othergeneric methods... what was it you want to do here?
所以现在我们有了double
通过泛型键入的值- 但除了调用其他泛型方法之外,我们仍然无能为力……你想在这里做什么?
回答by David Wengier
I can't think of why you'd want to cast as GetType(), because you wouldn't be able to do anything to useful with the result, without knowing the type at compile time anyway.
我想不出你为什么要强制转换为 GetType(),因为在编译时不知道类型的情况下,你将无法对结果做任何有用的事情。
Perhaps what you are looking for, is being able to Convert. If that is the case, the following should work for you:
也许您正在寻找的是能够转换。如果是这种情况,以下内容应该适合您:
object input = GetSomeInput();
object result = Convert.ChangeType(input, someOtherObject.GetType());
We use this when reading values from the registry which are all stored as strings, and then stuffing them into properties using reflection.
我们在从注册表中读取所有存储为字符串的值时使用它,然后使用反射将它们填充到属性中。
回答by Spence
You can use the Activator.CreateInstance
method to create an instance from a type.
您可以使用该Activator.CreateInstance
方法从类型创建实例。
FYI reflection is SLOOWWWW, so if you need to do this cast many times in a row, it may be better to define your types in an enum or something like this then create instances without using reflection.
仅供参考,反射是 SLOOWWWW,因此如果您需要连续多次执行此转换,最好在枚举或类似内容中定义您的类型,然后在不使用反射的情况下创建实例。
回答by Luke Hill
You can use getClass() which returns a Class object then use the cast method in the Class object to cast the object to an object of that Class's type, like so:
您可以使用 getClass() 返回一个 Class 对象,然后使用 Class 对象中的 cast 方法将该对象转换为该 Class 类型的对象,如下所示:
myObj.getClass().cast(myObj)
myObj.getClass().cast(myObj)
回答by jp2code
I have a class that I use for change tracking in my Windows Formsapp because not all items were databound. Most items were TextBoxcontrols, but there were ComboBoxand DateTimePickercontrols as well.
我有一个类用于在我的Windows 窗体应用程序中进行更改跟踪,因为并非所有项目都是databound。大多数项目是TextBox控件,但也有ComboBox和DateTimePicker控件。
For simplicity, my HasChanged
property tests the generic Windows.Forms.Controlto see if it is a ComboBox, but you could test whatever types of controls you add to your Windows Form.
为简单起见,我的HasChanged
属性测试通用Windows.Forms.Control以查看它是否为ComboBox,但您可以测试添加到 Windows 窗体的任何类型的控件。
Below is that class - if it helps for anyone.
下面是那个课程 - 如果它对任何人有帮助。
internal class DataItem
{
private static Color originalBackColor, changedBackColor, originalForeColor, changedForeColor;
private static Font originalFont, changedFont;
static DataItem()
{
originalBackColor = SystemColors.Control;
changedBackColor = SystemColors.HighlightText;
originalForeColor = Color.Black;
changedForeColor = Color.Red;
originalFont = new Font(FontFamily.GenericSansSerif, 12.5f);
changedFont = new Font(originalFont, FontStyle.Bold);
}
public static void ChangeSetup(Control original, Color changedBackgroundColor)
{
originalBackColor = original.BackColor;
originalForeColor = original.ForeColor;
originalFont = original.Font;
changedBackColor = changedBackgroundColor;
changedFont = new Font(originalFont, FontStyle.Bold);
}
private bool changeTracking;
public DataItem(Control control, Object value)
{
this.Control = control;
var current = String.Format("{0}", Control.Text).Trim();
if (Control is ComboBox)
{
var cbo = (ComboBox)Control;
current = cbo.StateGet();
}
this.OriginalValue = current;
this.Control.TextChanged += Control_TextChanged;
changeTracking = true;
}
public Control Control { get; private set; }
private void Control_TextChanged(Object sender, EventArgs e)
{
if (TrackingChanges)
{
if (HasChanged)
{
this.Control.BackColor = originalBackColor;
this.Control.Font = originalFont;
this.Control.ForeColor = originalForeColor;
}
else
{
this.Control.BackColor = changedBackColor;
this.Control.Font = changedFont;
this.Control.ForeColor = changedForeColor;
}
}
}
public bool HasChanged
{
get
{
var current = String.Format("{0}", Control.Text).Trim();
if (Control is ComboBox)
{
var cbo = (ComboBox)Control;
current = cbo.StateGet();
}
return !current.Equals(OriginalValue);
}
}
public String OriginalValue { get; private set; }
public void Reset()
{
changeTracking = false;
this.OriginalValue = String.Empty;
this.Control.Text = String.Empty;
this.Control.BackColor = originalBackColor;
this.Control.Font = originalFont;
this.Control.ForeColor = originalForeColor;
}
public bool TrackingChanges
{
get
{
return changeTracking;
}
}
}