当前位置:编程学习 > C#/ASP.NET >>

C#中怎样访问private?

C#中怎样访问private修饰的东西? --------------------编程问答-------------------- 反射 --------------------编程问答-------------------- private 关键字是一个成员访问修饰符。私有访问是允许的最低访问级别。私有成员只有在声明它们的类和结构体中才是可访问的 --------------------编程问答-------------------- 怎样用反射呢??? --------------------编程问答-------------------- private成员只允许内部访问
要外部使用请使用public修饰符 --------------------编程问答-------------------- private 就是不让在外部访问,你为什么要访问,要让能访问到,为什么不用public呢 --------------------编程问答-------------------- 都private了还访问什么? 这不反着干吗?

为private的字段加公开属性吧 --------------------编程问答-------------------- 一般是写一个public 的函数来操作private的变量  --------------------编程问答--------------------
//-----------------------------------------------------------------------
//  This file is part of the Microsoft .NET Framework SDK Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation.  See these other
//materials for detailed information regarding Microsoft code samples.
// 
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//
/*=====================================================================
  File:      Invoke.cs

  Summary:   Demonstrates how to use reflection invoke.

  Warning: This sample shows how to invoke ANY method via reflection on ANY location.
This can potentially be a security issue.
When implementing this pattern in your code be sure to take appropriate security measures,
such as hosting inside an AppDomain with locked down security permission.

=====================================================================*/




using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;

namespace Microsoft.Samples
{
public sealed class App
{
private App()
{
}

public static void Main(String[] args)
{
if (args.Length < 3)
{
Usage();
return;
}

Assembly assembly;
Type type;

try
{
// Load the requested assembly and get the requested type
assembly = Assembly.LoadFrom(args[0]);
type = assembly.GetType(args[1], true);
}
catch (FileNotFoundException)
{
Console.WriteLine("Could not load Assembly: \"{0}\"", args[0]);
return;
}
catch (TypeLoadException)
{
Console.WriteLine("Could not load Type: \"{0}\"\nfrom assembly: \"{1}\"", args[1], args[0]);
return;
}

// Get the methods from the type
MethodInfo[] methods = type.GetMethods();

if (methods == null)
{
Console.WriteLine("No Matching Types Found");
return;
}

// Make a new array that holds only the args for the call
String[] newArgs = new String[args.Length - 3];

if (newArgs.Length != 0)
{
Array.Copy(args, 3, newArgs, 0, newArgs.Length);
}

// Try each method for a match
StringBuilder failureExcuses = new StringBuilder();

foreach (MethodInfo m in methods)
{
Object obj = null;

try
{
obj = AttemptMethod(type, m, args[2], newArgs);
}
catch (CustomException e)
{
failureExcuses.Append(e.Message + "\n");
continue;
}

// If we make it this far without a throw, our job is done!
Console.WriteLine(obj);
return;
}

Console.WriteLine("Suitable method not found!");
Console.WriteLine("Here are the reasons:\n" + failureExcuses);
}

// Checks a method for a signature match, and invokes it if there is one
private static Object AttemptMethod(Type type, MethodInfo method, String name, String[] args)
{
// Name does not match?
if (String.Compare(method.Name, name, false, CultureInfo.InvariantCulture) != 0)
{
throw new CustomException(method.DeclaringType + "." + method.Name + ": Method Name Doesn't Match!");
}

// Wrong number of parameters?
ParameterInfo[] param = method.GetParameters();

if (param.Length != args.Length)
{
throw new CustomException(method.DeclaringType + "." + method.Name + ": Method Signatures Don't Match!");
}

// Ok, can we convert the strings to the right types?
Object[] newArgs = new Object[args.Length];

for (int index = 0; index < args.Length; index++)
{
try
{
newArgs[index] = Convert.ChangeType(args[index], param[index].ParameterType, CultureInfo.InvariantCulture);
}
catch (Exception e)
{
throw new CustomException(method.DeclaringType + "." + method.Name + ": Argument Conversion Failed", e);
}
}

// We made it this far, lets see if we need an instance of this type
Object instance = null;

if (!method.IsStatic)
{
instance = Activator.CreateInstance(type);
}

// ok, let's invoke this one!
return method.Invoke(instance, newArgs);
}

// Print usage
private static void Usage()
{
Console.WriteLine("Usage:\n" + "   Invoke [Assembly] [Type] [Method] [Parameters...]");
}

class CustomException : Exception
{
public CustomException(String m):base(m) { }

public CustomException(String m, Exception n):base(m,n) { }
}
}
}
--------------------编程问答-------------------- privat-私有变量! --------------------编程问答--------------------

    //楼主要这种效果?
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
--------------------编程问答-------------------- 不是上面大哥说的哪个效果!So Sorry!你那是字段  谢谢! --------------------编程问答-------------------- public的外部才可以访问 --------------------编程问答-------------------- private可以用反射访问 --------------------编程问答-------------------- System.Reflection.Assembly asm = System.Reflection.Assembly.Load(namespace);
asm.GetType().GetMethods()//获取public方法
asm.GetType().FindMembers(MemberTypes.Method, BindingFlags.Default|BindingFlags.NonPublic | BindingFlags.Instance , null, null);
//注意FindMembers的第二个参数,是Flag,他们必须与 Public 或 NonPublic 一起指定 Instance 或 Static,否则将不返回成员。 


估计应该可以成的吧

--------------------编程问答--------------------

Assembly ass = Assembly.Load("ConsoleApplication");

            object structInstance = ass.CreateInstance("ConsoleApplication.PrivateField");

            Type structType = structInstance.GetType();


            BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic; 

            FieldInfo fi = structType.GetField("ID",bf);

            Console.WriteLine("ID oldValue:{0}", fi.GetValue(structInstance));

            fi.SetValue(structInstance, 1);

            Console.WriteLine("ID newValue:{0}", fi.GetValue(structInstance));

            fi = structType.GetField("Name", bf);

            Console.WriteLine("Name oldValue:{0}", fi.GetValue(structInstance));

            fi.SetValue(structInstance, "Sandy");

            Console.WriteLine("Name newValue:{0}", fi.GetValue(structInstance));


namespace ConsoleApplication
{
    class PrivateField
    {
        private int ID = 0;
        private string Name = "";
    }
}
--------------------编程问答-------------------- 要是 设了private 又先在外部访问,那干脆 就public 吧, --------------------编程问答-------------------- 包装get/set对 --------------------编程问答-------------------- 我想请教一下,访问private达到什么目的 --------------------编程问答-------------------- 不明白
--------------------编程问答-------------------- 反射
属性,[成员]方法, --------------------编程问答-------------------- private僅類內部成員變量及成員函數訪問
--------------------编程问答-------------------- 反射可以。
楼主既然问,那必然是迫不得已得这样用了。我也遇到过这样的问题。实际情况是千变万化的。CSDN上真是,搜索到个问题的解决方法,一看是CSDN的,都不想来看。很少有人在回答,一堆人在废话。还给你解释一下private是私有的,谁TM不知道啊 --------------------编程问答-------------------- 类内部做一个接口间接访问不行吗 --------------------编程问答-------------------- 搞不懂,楼主什么意思。 --------------------编程问答-------------------- 封装.. --------------------编程问答-------------------- 封装处理
除非是研究反射知识。 --------------------编程问答-------------------- 一般是 声明一个字段是private的

private string _str;

然后提供一个public 的方法,来修改字段。比如

public void SetStr(string str)
{
  _str = str;
}

这样实现了隐藏了字段。但提供了修改这个字段的效果。 --------------------编程问答-------------------- 如果说的是方法

可以写个类来继承
继承的类就拥有了这个私有方法
在继承的类写个公共方法,利用反射来调用这个私有方法 --------------------编程问答-------------------- 用属性把! --------------------编程问答-------------------- 属性访问啊 --------------------编程问答-------------------- 如果要访问为什么要用private?public就好
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,