PropertyInfo.SetValue 方法(System.Reflection) | Microsoft Docs
文章推薦指數: 80 %
StaticProperty); // Get a type object that represents the Example type. Type examType = typeof(Example); // Change the static property value.
跳到主要內容
已不再支援此瀏覽器。
請升級至MicrosoftEdge,以利用最新功能、安全性更新和技術支援。
下載MicrosoftEdge
其他資訊
目錄
結束焦點模式
語言
閱讀英文
儲存
編輯
共用
Twitter
LinkedIn
Facebook
電子郵件
WeChat
目錄
語言
語言
閱讀英文
儲存
目錄
閱讀英文
儲存
編輯
Twitter
LinkedIn
Facebook
電子郵件
WeChat
目錄
PropertyInfo.SetValue方法
參考
此頁面有所助益嗎?
Yes
No
還有其他意見反應嗎?
系統會將意見反應傳送給Microsoft:按下[提交]按鈕,您的意見反應將用來改善Microsoft產品和服務。
隱私權原則。
送出
謝謝。
定義
命名空間:
System.Reflection
組件:System.Reflection.dll
組件:System.Runtime.dll
組件:mscorlib.dll
組件:netstandard.dll
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。
Microsoft對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
設定指定之物件的屬性值。
本文內容
多載
SetValue(Object,Object)
設定指定之物件的屬性值。
SetValue(Object,Object,Object[])
使用索引屬性的選擇性索引值,設定指定的物件的屬性值。
SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo)
當在衍生類別中覆寫時,設定指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。
SetValue(Object,Object)
設定指定之物件的屬性值。
public:
voidSetValue(System::Object^obj,System::Object^value);
publicvoidSetValue(objectobj,objectvalue);
publicvoidSetValue(object?obj,object?value);
memberthis.SetValue:obj*obj->unit
PublicSubSetValue(objAsObject,valueAsObject)
參數
obj
Object
將設定其屬性值的物件。
value
Object
新的屬性值。
例外狀況
ArgumentException
找不到屬性的set存取子。
-或-
value無法轉換成PropertyType類型。
TargetException
obj類型不符合目標類型,或屬性是執行個體屬性但obj為null。
注意:在.net中,WindowsStore應用程式或便攜類別庫中,改為攔截Exception。
MethodAccessException
曾不合法嘗試存取類別內的私用或保護方法。
注意:在.net中WindowsStore應用程式或可移植類別庫中,改為攔截基類例外狀況MemberAccessException。
TargetInvocationException
設定屬性值時發生錯誤。
InnerException屬性指出錯誤的原因。
範例
下列範例會宣告一個名為Example的類別,其中包含一個staticSharedVisualBasic)的(和一個實例屬性。
此範例會使用SetValue(Object,Object)方法來變更原始的屬性值,並顯示原始和最終的值。
usingnamespaceSystem;
usingnamespaceSystem::Reflection;
refclassExample
{
private:
intstatic_sharedProperty=41;
int_instanceProperty;
public:
Example()
{
_instanceProperty=42;
};
staticpropertyintSharedProperty
{
intget(){return_sharedProperty;}
voidset(intvalue){_sharedProperty=value;}
};
propertyintInstanceProperty
{
intget(){return_instanceProperty;}
voidset(intvalue){_instanceProperty=value;}
};
};
voidmain()
{
Console::WriteLine("Initialvalueofstaticproperty:{0}",
Example::SharedProperty);
PropertyInfo^piShared=
Example::typeid->GetProperty("SharedProperty");
piShared->SetValue(nullptr,76,nullptr);
Console::WriteLine("Newvalueofstaticproperty:{0}",
Example::SharedProperty);
Example^exam=gcnewExample();
Console::WriteLine("\nInitialvalueofinstanceproperty:{0}",
exam->InstanceProperty);
PropertyInfo^piInstance=
Example::typeid->GetProperty("InstanceProperty");
piInstance->SetValue(exam,37,nullptr);
Console::WriteLine("Newvalueofinstanceproperty:{0}",
exam->InstanceProperty);
};
/*Theexampledisplaysthefollowingoutput:
Initialvalueofstaticproperty:41
Newvalueofstaticproperty:76
Initialvalueofinstanceproperty:42
Newvalueofinstanceproperty:37
*/
usingSystem;
usingSystem.Reflection;
classExample
{
privatestaticint_staticProperty=41;
privateint_instanceProperty=42;
//Declareapublicstaticproperty.
publicstaticintStaticProperty
{
get{return_staticProperty;}
set{_staticProperty=value;}
}
//Declareapublicinstanceproperty.
publicintInstanceProperty
{
get{return_instanceProperty;}
set{_instanceProperty=value;}
}
publicstaticvoidMain()
{
Console.WriteLine("Initialvalueofstaticproperty:{0}",
Example.StaticProperty);
//GetatypeobjectthatrepresentstheExampletype.
TypeexamType=typeof(Example);
//Changethestaticpropertyvalue.
PropertyInfopiShared=examType.GetProperty("StaticProperty");
piShared.SetValue(null,76);
Console.WriteLine("Newvalueofstaticproperty:{0}",
Example.StaticProperty);
//CreateaninstanceoftheExampleclass.
Exampleexam=newExample();
Console.WriteLine("\nInitialvalueofinstanceproperty:{0}",
exam.InstanceProperty);
//Changetheinstancepropertyvalue.
PropertyInfopiInstance=examType.GetProperty("InstanceProperty");
piInstance.SetValue(exam,37);
Console.WriteLine("Newvalueofinstanceproperty:{0}",
exam.InstanceProperty);
}
}
//Theexampledisplaysthefollowingoutput:
//Initialvalueofstaticproperty:41
//Newvalueofstaticproperty:76
//
//Initialvalueofinstanceproperty:42
//Newvalueofinstanceproperty:37
ImportsSystem.Reflection
ClassExample
PrivateShared_sharedPropertyAsInteger=41
Private_instancePropertyAsInteger=42
'Declareapublicstatic(shared)property.
PublicSharedPropertySharedPropertyAsInteger
Get
Return_sharedProperty
EndGet
Set
_sharedProperty=Value
EndSet
EndProperty
'Declareapublicinstanceproperty.
PublicPropertyInstancePropertyAsInteger
Get
Return_instanceProperty
EndGet
Set
_instanceProperty=Value
EndSet
EndProperty
PublicSharedSubMain()
Console.WriteLine("Initialvalueofsharedproperty:{0}",
Example.SharedProperty)
'GetatypeobjectthatrepresentstheExampletype.
DimexamTypeAsType=GetType(Example)
'Changethestatic(shared)propertyvalue.
DimpiSharedAsPropertyInfo=examType.GetProperty("SharedProperty")
piShared.SetValue(Nothing,76)
Console.WriteLine("Newvalueofsharedproperty:{0}",
Example.SharedProperty)
Console.WriteLine()
'CreateaninstanceoftheExampleclass.
DimexamAsNewExample
Console.WriteLine("Initialvalueofinstanceproperty:{0}",
exam.InstanceProperty)
'Changetheinstancepropertyvalue.
DimpiInstanceAsPropertyInfo=examType.GetProperty("InstanceProperty")
piInstance.SetValue(exam,37)
Console.WriteLine("Newvalueofinstanceproperty:{0}",_
exam.InstanceProperty)
EndSub
EndClass
'Theexampledisplaysthefollowingoutput:
'Initialvalueofsharedproperty:41
'Newvalueofsharedproperty:76
'
'Initialvalueofinstanceproperty:42
'Newvalueofinstanceproperty:37
備註
多載會SetValue(Object,Object)設定非索引屬性的值。
若要判斷是否已編制索引屬性,請呼叫GetIndexParameters方法。
如果產生的陣列有0(零)元素,則不會編制屬性的索引。
若要設定已編制索引之屬性的值,請呼叫多載SetValue(Object,Object,Object[])。
如果這個物件的屬性型別PropertyInfo是實值型別,而且value是null,則屬性會設定為該型別的預設值。
這是一個便利的方法,它會呼叫抽象方法的執行時間執行SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo),BindingFlags.DefaultBindingFlags並指定參數、fornullBinder、nullforObject[]和nullCultureInfo。
若要使用SetValue方法,請先取得Type代表類別的物件。
從Type取得PropertyInfo物件。
從PropertyInfo物件呼叫SetValue方法。
注意
從.NETFramework2.0ServicePack1開始,如果呼叫者已被授ReflectionPermission與旗標,ReflectionPermissionFlag.RestrictedMemberAccess且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。
(查看反映的安全性考慮。
)
若要使用此功能,您的應用程式應該以.NETFramework3.5或更新版本為目標。
適用於
SetValue(Object,Object,Object[])
使用索引屬性的選擇性索引值,設定指定的物件的屬性值。
public:
virtualvoidSetValue(System::Object^obj,System::Object^value,cli::array<:object>^index);
publicvirtualvoidSetValue(objectobj,objectvalue,object[]index);
publicvirtualvoidSetValue(object?obj,object?value,object?[]?index);
abstractmemberSetValue:obj*obj*obj[]->unit
overridethis.SetValue:obj*obj*obj[]->unit
PublicOverridableSubSetValue(objAsObject,valueAsObject,indexAsObject())
參數
obj
Object
將設定其屬性值的物件。
value
Object
新的屬性值。
index
Object[]
索引屬性的選擇性索引值。
非索引屬性的這個值應為null。
實作
SetValue(Object,Object,Object[])
例外狀況
ArgumentException
index陣列未包含所需的引數類型。
-或-
找不到屬性的set存取子。
-或-
value無法轉換成PropertyType類型。
TargetException
物件不符合目標類型,或屬性是執行個體屬性但obj為null。
注意:在.net中,WindowsStore應用程式或便攜類別庫中,改為攔截Exception。
TargetParameterCountException
index中的參數數目不符合索引屬性所接受的參數數目。
MethodAccessException
曾不合法嘗試存取類別內的私用或保護方法。
注意:在.net中WindowsStore應用程式或可移植類別庫中,改為攔截基類例外狀況MemberAccessException。
TargetInvocationException
設定屬性值時發生錯誤。
例如,為索引屬性指定的索引值超出範圍。
InnerException屬性指出錯誤的原因。
範例
下列範例會定義名為TestClass的類別,該類別具有名為的讀寫屬性Caption。
它會顯示內容的預設值Caption、呼叫SetValue方法來變更屬性值,以及顯示結果。
usingnamespaceSystem;
usingnamespaceSystem::Reflection;
//Defineaproperty.
publicrefclassTestClass
{
private:
String^caption;
public:
TestClass()
{
caption="ADefaultcaption";
}
propertyString^Caption
{
String^get()
{
returncaption;
}
voidset(String^value)
{
if(caption!=value)
{
caption=value;
}
}
}
};
intmain()
{
TestClass^t=gcnewTestClass;
//GetthetypeandPropertyInfo.
Type^myType=t->GetType();
PropertyInfo^pinfo=myType->GetProperty("Caption");
//Displaythepropertyvalue,usingtheGetValuemethod.
Console::WriteLine("\nGetValue:{0}",pinfo->GetValue(t,nullptr));
//UsetheSetValuemethodtochangethecaption.
pinfo->SetValue(t,"Thiscaptionhasbeenchanged.",nullptr);
//Displaythecaptionagain.
Console::WriteLine("GetValue:{0}",pinfo->GetValue(t,nullptr));
Console::WriteLine("\nPresstheEnterkeytocontinue.");
Console::ReadLine();
return0;
}
/*
Thisexampleproducesthefollowingoutput:
GetValue:ADefaultcaption
GetValue:Thiscaptionhasbeenchanged
PresstheEnterkeytocontinue.
*/
usingSystem;
usingSystem.Reflection;
//Defineaclasswithaproperty.
publicclassTestClass
{
privatestringcaption="ADefaultcaption";
publicstringCaption
{
get{returncaption;}
set
{
if(caption!=value)
{
caption=value;
}
}
}
}
classTestPropertyInfo
{
publicstaticvoidMain()
{
TestClasst=newTestClass();
//GetthetypeandPropertyInfo.
TypemyType=t.GetType();
PropertyInfopinfo=myType.GetProperty("Caption");
//Displaythepropertyvalue,usingtheGetValuemethod.
Console.WriteLine("\nGetValue:"+pinfo.GetValue(t,null));
//UsetheSetValuemethodtochangethecaption.
pinfo.SetValue(t,"Thiscaptionhasbeenchanged.",null);
//Displaythecaptionagain.
Console.WriteLine("GetValue:"+pinfo.GetValue(t,null));
Console.WriteLine("\nPresstheEnterkeytocontinue.");
Console.ReadLine();
}
}
/*
Thisexampleproducesthefollowingoutput:
GetValue:ADefaultcaption
GetValue:Thiscaptionhasbeenchanged
PresstheEnterkeytocontinue.
*/
ImportsSystem.Reflection
'Defineaclasswithaproperty.
PublicClassTestClass
PrivatemyCaptionAsString="ADefaultcaption"
PublicPropertyCaption()AsString
Get
ReturnmyCaption
EndGet
Set
IfmyCaption<>valueThenmyCaption=value
EndSet
EndProperty
EndClass
PublicClassTestPropertyInfo
PublicSharedSubMain()
DimtAsNewTestClass()
'GetthetypeandPropertyInfo.
DimmyTypeAsType=t.GetType()
DimpinfoAsPropertyInfo=myType.GetProperty("Caption")
'Displaythepropertyvalue,usingtheGetValuemethod.
Console.WriteLine(vbCrLf&"GetValue:"&pinfo.GetValue(t,Nothing))
'UsetheSetValuemethodtochangethecaption.
pinfo.SetValue(t,"Thiscaptionhasbeenchanged.",Nothing)
'Displaythecaptionagain.
Console.WriteLine("GetValue:"&pinfo.GetValue(t,Nothing))
Console.WriteLine(vbCrLf&"PresstheEnterkeytocontinue.")
Console.ReadLine()
EndSub
EndClass
'Thisexampleproducesthefollowingoutput:
'
'GetValue:ADefaultcaption
'GetValue:Thiscaptionhasbeenchanged
'
'PresstheEnterkeytocontinue.
請注意,因為屬性不是Caption參數陣列,所以index引數為null。
下列範例會宣告一個名為Example的類別,其中包含三個屬性:staticSharedVisualBasic)中的屬性(、實例屬性和索引的實例屬性。
此範例會使用SetValue方法來變更屬性的預設值,並顯示原始和最終的值。
使用反映來搜尋已編制索引之實例屬性的名稱,會根據語言以及套用至屬性的屬性而不同。
在VisualBasic中,一律會使用屬性名稱來搜尋具有反映的屬性。
您可以使用Default關鍵字將屬性設為預設的索引屬性,在此情況下,您可以在存取屬性時省略名稱,如此範例所示。
您也可以使用屬性名稱。
在c#中,已編制索引的實例屬性是稱為索引子的預設屬性,而且在存取程式碼中的屬性時,絕對不會使用該名稱。
根據預設,屬性的名稱為Item,而且當您使用反映來搜尋屬性時,必須使用該名稱。
您可以使用IndexerNameAttribute屬性,為索引子提供不同的名稱。
在這個範例中,名稱為IndexedInstanceProperty。
在c++中,此default規範可用來讓索引屬性成為預設索引屬性(類別索引子)。
在此情況下,屬性的名稱預設為Item,而且當您使用反映來搜尋屬性時,您必須使用該名稱,如此範例所示。
您可以使用IndexerNameAttribute屬性在反映中為類別索引子提供不同的名稱,但您無法使用該名稱來存取程式碼中的屬性。
不是類別索引子的索引屬性,會在程式碼和反映中使用其名稱進行存取。
usingnamespaceSystem;
usingnamespaceSystem::Reflection;
usingnamespaceSystem::Collections::Generic;
refclassExample
{
private:
intstatic_sharedProperty=41;
int_instanceProperty;
Dictionary
延伸文章資訊
- 1使用屬性- C# 程式設計手冊 - Microsoft Docs
class Person { private string _name; // the name field public string Name // the Name property { ...
- 2Setting a property by reflection with a string value - Stack ...
I'd like to set a property of an object through Reflection, with a value of type string . So, for...
- 3c# property set value Code Example
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
- 4PropertyInfo.SetValue 方法(System.Reflection) | Microsoft Docs
StaticProperty); // Get a type object that represents the Example type. Type examType = typeof(Ex...
- 5C# PropertyInfo.SetValue方法代碼示例- 純淨天空
SetValue方法的20個代碼示例,這些例子默認根據受歡迎程度排序。 ... I/F public bool SetPropertyValue(object component, Proper...