В Java все переменные, которые вы объявляете, на самом деле являются «ссылками» на объекты (или примитивы), а не самими объектами.
При попытке выполнить один метод объекта , ссылка просит живой объект выполнить этот метод. Но если ссылка ссылается на NULL (ничего, нуль, void, nada), то нет способа, которым метод будет выполнен. Тогда runtime сообщит вам об этом, выбросив исключение NullPointerException.
Ваша ссылка «указывает» на нуль, таким образом, «Null -> Pointer».
Объект живет в памяти виртуальной машины пространство и единственный способ доступа к нему - использовать ссылки this
. Возьмем этот пример:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
И в другом месте вашего кода:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
Это важно знать - когда больше нет ссылок на объект (в пример выше, когда reference
и otherReference
оба указывают на null), тогда объект «недоступен». Мы не можем работать с ним, поэтому этот объект готов к сбору мусора, и в какой-то момент VM освободит память, используемую этим объектом, и выделит другую.
Вы могли использовать:
from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName
Это перечислит все диски в системе без LINQ, но все еще использования WMI:
// browse all USB WMI physical disks
foreach(ManagementObject drive in new ManagementObjectSearcher(
"select * from Win32_DiskDrive where InterfaceType='USB'").Get())
{
// associate physical disks with partitions
foreach(ManagementObject partition in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"]
+ "'} WHERE AssocClass =
Win32_DiskDriveToDiskPartition").Get())
{
Console.WriteLine("Partition=" + partition["Name"]);
// associate partitions with logical disks (drive letter volumes)
foreach(ManagementObject disk in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
+ partition["DeviceID"]
+ "'} WHERE AssocClass =
Win32_LogicalDiskToPartition").Get())
{
Console.WriteLine("Disk=" + disk["Name"]);
}
}
// this may display nothing if the physical disk
// does not have a hardware serial number
Console.WriteLine("Serial="
+ new ManagementObject("Win32_PhysicalMedia.Tag='"
+ drive["DeviceID"] + "'")["SerialNumber"]);
}
Версия C# 2.0 кода Кента (от вершины моей головы, не протестированной):
IList<String> fullNames = new List<String>();
foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) {
if (driveInfo.DriveType == DriveType.Removable) {
fullNames.Add(driveInfo.RootDirectory.FullName);
}
}