Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET:如何获取空对象的类型?_C#_.net_Types_Gettype - Fatal编程技术网

C# .NET:如何获取空对象的类型?

C# .NET:如何获取空对象的类型?,c#,.net,types,gettype,C#,.net,Types,Gettype,我有一个带有out参数的方法,它尝试进行类型转换。基本上: public void GetParameterValue(out object destination) { object paramVal = "I want to return this. could be any type, not just string."; destination = null; // default out param to null destination = Convert.

我有一个带有out参数的方法,它尝试进行类型转换。基本上:

public void GetParameterValue(out object destination)
{
    object paramVal = "I want to return this. could be any type, not just string.";

    destination = null; // default out param to null
    destination = Convert.ChangeType(paramVal, destination.GetType());
}
问题是,通常有人会这样称呼:

string output;
GetParameterValue(output);
这将失败,因为:

destination.GetType()
目标为空,因此无法对其调用
.GetType()
。我们也不能称之为:

typeof(destination)
因为目标是变量名而不是类型名

那么,有没有办法获取设置为null的对象的类型?我认为必须有一种方法可以在不分配任何内容的情况下知道存储位置的类型


为了提供更多的信息,我正在尝试创建一个实用方法来获取Oracle存储过程的输出参数。问题在于
DbParameter.Value
属于object类型

开发人员最理想的做法是:

string val = GetParameterValue("parameterName");
值得注意的是,没有类型转换。实际上,您不知道“equals”的LPRAM,因此我选择了:

string val;
GetParameterValue("parameterName", out val);
在方法中,我知道输出变量的目标类型。我想这是个错误的假设。作为替代方案,我还编写了以下方法:

public T GetParameterValue<T>(string paramName)

整个想法是不必在多个位置显式使用该类型,因此,如果数据类型发生更改,则只需在目标对象(
MyObj.SomeProp
)和数据库中对其进行更改。必须有更好的方法…

在您的示例中,
System.Object类型的值应该为null


你的例子编译了吗?我收到一个“无法从'out string'转换为'out object'”错误。

目标变量的类型始终是
System.object
。你可以回来

Convert.ChangeType(paramVal, System.Object).

目前,您无法知道传递到方法中的内容。您可以将其转换为以下通用方法:

public void GetParameterValue<T>(out T destination)
{
   ...
}
MyObj.SomeProp = GetParameterValue("parameterName", MyObj.SomeProp);
public void GetParameterValue(out T destination)
{
...
}
那么,有没有办法获取设置为null的对象的类型?我认为必须有一种方法可以在不分配任何内容的情况下知道存储位置的类型

不一定。最好的说法是它是一个
对象
null
引用不指向任何存储位置,因此没有元数据可供确定

您最好将其更改为更通用,如:

public void GetParameterValue<T>(out T destination)
{
    object paramVal = "Blah";
    destination = default(T);
    destination = Convert.ChangeType(paramVal, typeof(T));
}
public void GetParameterValue(out T destination)
{
对象paramVal=“Blah”;
目的地=默认值(T);
destination=Convert.ChangeType(paramVal,typeof(T));
}

可以推断出
T
的类型,因此不需要显式地为方法指定类型参数。

我认为当值为null时,不可能获取类型。另外,由于您是在GetParameterValue内部调用,所以最好(当值为null时)获取“destination”参数的类型,即“object”。您可以考虑将类型作为参数传递给GETValueRealValk,在这里您可以获得更多信息,如:

public void GetParameterValue(Type sourceType, out object destination) { //... }

如果您不介意将您的方法声明为泛型,那么这是可能的。试试这个

class Program
{
    public static void GetParameterValue<T>(out T destination)
    {
        Console.WriteLine("typeof(T)=" + typeof(T).Name);
        destination = default(T);
    }
    static void Main(string[] args)
    {
        string s;
        GetParameterValue(out s);
        int i;
        GetParameterValue(out i);
    }
}
类程序
{
公共静态void GetParameterValue(out T destination)
{
Console.WriteLine(“typeof(T)=”+typeof(T).Name);
目的地=默认值(T);
}
静态void Main(字符串[]参数)
{
字符串s;
GetParameterValue(输出s);
int i;
GetParameterValue(输出i);
}
}

如果没有实例,则没有实例类型

您最好使用引用的类型,这意味着如果您有一个对象引用(如问题中的方法),则引用类型为object


您可能不应该尝试将一种类型的空实例转换为另一种类型的空实例…

@Rally25s:

string val;
GetParameterValue("parameterName", out val);
从你的信息中(在回答中)不清楚这个问题是什么。如果声明为:

void GetParameterValue<T>(string parameterName, out T val)  { }
这是相当困难的,但不是所提出的更糟糕的方法


一个不同的方法,我在C++中使用过,但是在C语言中还没有尝试过,它有一个自己的设计对象GETValueValueAudio(),然后为它实现一些隐式的铸造算子。

class ParameterHelper
{
   private object value;
   public ParameterHelper(object value)   { this.value = value;  }

   public static implicit operator int(ParameterHelper v)
     { return (int) v.value; }

}
ParameterHelper GetParameterValue( string parameterName);

MyObj.SomeProp = GetParameterValue("parameterName");

从理论上讲,空指针不是和C中的空指针一样吗?也就是说,它持有一个内存地址,就是这样?如果是这样的话,那么它类似于数学中被零除的情况,结果是未定义的

可以对该行执行以下操作:

string val = GetParameterValue<string>("parameterName");
string val=GetParameterValue(“parameterName”);
只需删除第一个字符串,现在就没有重复:

var val = GetParameterValue<string>("parameterName");
var val=GetParameterValue(“parameterName”);
不一定是你想要的,尽管有一个问题是如何解释null?

//**工作答案**
//**The working answer**

//**based on your discussion eheheheheeh**

public void s<T>(out T varName)
{
    if (typeof (T) == typeof(HtmlTable)) 
    { 
         //////////       
    }

}

protected void Page_Load(object sender, EventArgs e) 
{
    HtmlTable obj=null ;
    s(out obj);       
}
//**基于你的讨论** 公共void s(out T varName) { if(typeof(T)=typeof(HtmlTable)) { ////////// } } 受保护的无效页面加载(对象发送方、事件参数e) { HtmlTable obj=null; s(out obj); }


这样,我们就可以使用switch来管理不同的属性类型。

以下扩展方法返回其声明的参数类型,而不管其内容如何:

using System;

namespace MyNamespace
{
    public static class Extensions
    {
        /// <summary>
        /// Gets the declared type of the specified object.
        /// </summary>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <param name="obj">The object.</param>
        /// <returns>
        /// A <see cref="Type"/> object representing type 
        /// <typeparamref name="T"/>; i.e., the type of <paramref name="obj"/> 
        /// as it was declared. Note that the contents of 
        /// <paramref name="obj"/> are irrelevant; if <paramref name="obj"/> 
        /// contains an object whose class is derived from 
        /// <typeparamref name="T"/>, then <typeparamref name="T"/> is 
        /// returned, not the derived type.
        /// </returns>
        public static Type GetDeclaredType<T>(
            this T obj )
        {
            return typeof( T );
        }
    }
}
请注意,
myObjType
myNullObjType
都将设置为System.Object,而不是System.String

如果您确实希望obj的内容类型不为空,则将
返回
行更改为:

return (obj != null) ? obj.GetType() : typeof( T );

好建议!第二个参数应该是typeof(T),而不是typeof(T).GetType()。不幸的是,代码“out T dest”无法编译,因为它找不到类型“T”。我将进一步研究这个选项…@rally25rs:T是一个泛型类型,在这种情况下,建议您使用泛型来确定方法的类型
var val = GetParameterValue<string>("parameterName");
//**The working answer**

//**based on your discussion eheheheheeh**

public void s<T>(out T varName)
{
    if (typeof (T) == typeof(HtmlTable)) 
    { 
         //////////       
    }

}

protected void Page_Load(object sender, EventArgs e) 
{
    HtmlTable obj=null ;
    s(out obj);       
}
private Hashtable propertyTable = new Hashtable();

public void LoadPropertyTypes()
{
    Type t = this.GetType();

    System.Reflection.MemberInfo[] memberInfo = t.GetMembers();

    foreach (System.Reflection.MemberInfo mInfo in memberInfo)
    {
        string[] prop = mInfo.ToString().Split(Convert.ToChar(" "));
        propertyTable.Add(prop[1], prop[0]);
    }
}
public string GetMemberType(string propName)
{
    if (propertyTable.ContainsKey(propName))
    {
        return Convert.ToString(propertyTable[propName]);
    }
    else{
        return "N/A";
    }
}
using System;

namespace MyNamespace
{
    public static class Extensions
    {
        /// <summary>
        /// Gets the declared type of the specified object.
        /// </summary>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <param name="obj">The object.</param>
        /// <returns>
        /// A <see cref="Type"/> object representing type 
        /// <typeparamref name="T"/>; i.e., the type of <paramref name="obj"/> 
        /// as it was declared. Note that the contents of 
        /// <paramref name="obj"/> are irrelevant; if <paramref name="obj"/> 
        /// contains an object whose class is derived from 
        /// <typeparamref name="T"/>, then <typeparamref name="T"/> is 
        /// returned, not the derived type.
        /// </returns>
        public static Type GetDeclaredType<T>(
            this T obj )
        {
            return typeof( T );
        }
    }
}
string myString = "abc";
object myObj = myString;
Type myObjType = myObj.GetDeclaredType();

string myNullString = null;
object myNullObj = myNullString;
Type myNullObjType = myNullObj.GetDeclaredType();
return (obj != null) ? obj.GetType() : typeof( T );