将typeof(Type)与System.RuntimeType

时间:2017-12-18 03:21:39

标签: c#

首先,我确实有一个解决这个问题的方法(使用type.FullName),所以它只是为了感兴趣。

*编辑澄清;这实际上只是比较代码中Type类型的最佳方法的问题。

object o;
Type t = typeof(someclass);
o = t;

// Cant do this
if (o.GetType() == typeof(RuntimeType)) {
}

附加到o的对象可以是任何东西,包括类型。我正在检查对象的类型,以了解如何进一步处理它。所以,如果它是一个字符串,我可以做一件事,如果它是一个枚举别的东西,如果它是一个类型,还有别的东西。我基本上处理与String.Format("",x,y,z)相同的事情,其中​​参数都是完全任意的。

我可以写

if (o.GetType().FullName == "System.RuntimeType") {} or
if (o.GetType()== typeof(Type).GetType()) {}

但两者看起来都很难看(尽管它很有效)。

原始问题:

如果之前已经问过这个问题,请道歉,但我找不到完全匹配(我有很多如何获得一种对象,对象是类或对象.GetType()样式问题。)

这个问题很接近,但它并不完全相同,因为我不能避免在类型上调用GetType(我不会想到?希望我不会忽视一些非常简单或欺骗的东西......); What's the difference between System.Type and System.RuntimeType in C#?

基本上,我已经创建了一个具有任意数量参数的属性。这些可以是任何对象,包括类型(我使用类型来决定应该如何处理属性附加到的属性)。例如,虽然属性可以是整数,但此整数是某个特定表的数据库中的主键。如果我将这种类型分配给属性,我可以编写通用代码来处理任何类型的对象,而无需编写大量的特殊情况代码。也就是说,我可以使用字符串,或任何其他值,如枚举,但由于模型已经存在,似乎没有任何意义,因为我可以使用Activator.CreateContext()基于它创建它们的实例传入的类型。

[AttributeUsage(AttributeTargets.Property)]
public class SomeAttribute: System.Attribute
{
    public SomeAttribute(params object[] parameters)
    {
        foreach(var p in parameters) {
            ...
            // Type of Type.  Uh oh.
            Type t = p.GetType();

            // Evaluates as false when t is of type Type(its actually RuntimeType, with is protected). Sad face.
            if (t == typeof(Type)) {
                ...
            }
            ...
        }
    }
}

我在某些属性上打了这个属性;

public class someclass
{
    [SomeAttribute(..., typeof(someotherclass))
    public sometype someproperty { get; set; }
}

当程序到达时

if (t == typeof(Type))

如果总是返回false。 t的类型被评估为System.RuntimeType而不是System.Type。不幸的是我不能把它改成

if (t == typeof(RuntimeType))

因为我得到编译错误"' RuntimeType'由于其保护等级而无法进入"

有没有办法在RuntimeType上执行类型匹配,而不是通过查看type.Name或type.FullName?

*需要进行更多澄清。

2 个答案:

答案 0 :(得分:3)

Consider Type is a normal class.

Type t1 = typeof(string);
Type t2 = "1".GetType();

There's no difference between t1 and t2. And What is t1? Just consider t1 or t2 as a normal object and the type of the object is System.Type. It means that t1 or t2 nearly equals new Type("System.String").

How can I know an object obj is aStringBuilder?

Just use is or as:

bool objIsStringBuilder = obj is StringBuilder;

How can I know t1 is a Type?

In the same way:

bool t1IsType = t1 is Type;

What is typeof(Type) or t1.GetType()?

Type t3 = typeof(Type);

Then t3 is nearly equals new Type("System.Type"). So of course t1 and t3 are not equal.

答案 1 :(得分:0)

我想我今天早上应该喝更多咖啡或睡觉。这虽然看起来和使用type.FullName一样错误。

if (t == typeof(Type).GetType()) {
}

哦,好吧。

相关问题